1:mod:`subprocess` --- Subprocess management 2=========================================== 3 4.. module:: subprocess 5 :synopsis: Subprocess management. 6 7.. moduleauthor:: Peter Åstrand <[email protected]> 8.. sectionauthor:: Peter Åstrand <[email protected]> 9 10**Source code:** :source:`Lib/subprocess.py` 11 12-------------- 13 14The :mod:`subprocess` module allows you to spawn new processes, connect to their 15input/output/error pipes, and obtain their return codes. This module intends to 16replace several older modules and functions:: 17 18 os.system 19 os.spawn* 20 21Information about how the :mod:`subprocess` module can be used to replace these 22modules and functions can be found in the following sections. 23 24.. seealso:: 25 26 :pep:`324` -- PEP proposing the subprocess module 27 28.. include:: ../includes/wasm-notavail.rst 29 30Using the :mod:`subprocess` Module 31---------------------------------- 32 33The recommended approach to invoking subprocesses is to use the :func:`run` 34function for all use cases it can handle. For more advanced use cases, the 35underlying :class:`Popen` interface can be used directly. 36 37 38.. function:: run(args, *, stdin=None, input=None, stdout=None, stderr=None,\ 39 capture_output=False, shell=False, cwd=None, timeout=None, \ 40 check=False, encoding=None, errors=None, text=None, env=None, \ 41 universal_newlines=None, **other_popen_kwargs) 42 43 Run the command described by *args*. Wait for command to complete, then 44 return a :class:`CompletedProcess` instance. 45 46 The arguments shown above are merely the most common ones, described below 47 in :ref:`frequently-used-arguments` (hence the use of keyword-only notation 48 in the abbreviated signature). The full function signature is largely the 49 same as that of the :class:`Popen` constructor - most of the arguments to 50 this function are passed through to that interface. (*timeout*, *input*, 51 *check*, and *capture_output* are not.) 52 53 If *capture_output* is true, stdout and stderr will be captured. 54 When used, the internal :class:`Popen` object is automatically created with 55 ``stdout=PIPE`` and ``stderr=PIPE``. The *stdout* and *stderr* arguments may 56 not be supplied at the same time as *capture_output*. If you wish to capture 57 and combine both streams into one, use ``stdout=PIPE`` and ``stderr=STDOUT`` 58 instead of *capture_output*. 59 60 The *timeout* argument is passed to :meth:`Popen.communicate`. If the timeout 61 expires, the child process will be killed and waited for. The 62 :exc:`TimeoutExpired` exception will be re-raised after the child process 63 has terminated. 64 65 The *input* argument is passed to :meth:`Popen.communicate` and thus to the 66 subprocess's stdin. If used it must be a byte sequence, or a string if 67 *encoding* or *errors* is specified or *text* is true. When 68 used, the internal :class:`Popen` object is automatically created with 69 ``stdin=PIPE``, and the *stdin* argument may not be used as well. 70 71 If *check* is true, and the process exits with a non-zero exit code, a 72 :exc:`CalledProcessError` exception will be raised. Attributes of that 73 exception hold the arguments, the exit code, and stdout and stderr if they 74 were captured. 75 76 If *encoding* or *errors* are specified, or *text* is true, 77 file objects for stdin, stdout and stderr are opened in text mode using the 78 specified *encoding* and *errors* or the :class:`io.TextIOWrapper` default. 79 The *universal_newlines* argument is equivalent to *text* and is provided 80 for backwards compatibility. By default, file objects are opened in binary mode. 81 82 If *env* is not ``None``, it must be a mapping that defines the environment 83 variables for the new process; these are used instead of the default 84 behavior of inheriting the current process' environment. It is passed 85 directly to :class:`Popen`. This mapping can be str to str on any platform 86 or bytes to bytes on POSIX platforms much like :data:`os.environ` or 87 :data:`os.environb`. 88 89 Examples:: 90 91 >>> subprocess.run(["ls", "-l"]) # doesn't capture output 92 CompletedProcess(args=['ls', '-l'], returncode=0) 93 94 >>> subprocess.run("exit 1", shell=True, check=True) 95 Traceback (most recent call last): 96 ... 97 subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1 98 99 >>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True) 100 CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0, 101 stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'') 102 103 .. versionadded:: 3.5 104 105 .. versionchanged:: 3.6 106 107 Added *encoding* and *errors* parameters 108 109 .. versionchanged:: 3.7 110 111 Added the *text* parameter, as a more understandable alias of *universal_newlines*. 112 Added the *capture_output* parameter. 113 114 .. versionchanged:: 3.11.3 115 116 Changed Windows shell search order for ``shell=True``. The current 117 directory and ``%PATH%`` are replaced with ``%COMSPEC%`` and 118 ``%SystemRoot%\System32\cmd.exe``. As a result, dropping a 119 malicious program named ``cmd.exe`` into a current directory no 120 longer works. 121 122.. class:: CompletedProcess 123 124 The return value from :func:`run`, representing a process that has finished. 125 126 .. attribute:: args 127 128 The arguments used to launch the process. This may be a list or a string. 129 130 .. attribute:: returncode 131 132 Exit status of the child process. Typically, an exit status of 0 indicates 133 that it ran successfully. 134 135 A negative value ``-N`` indicates that the child was terminated by signal 136 ``N`` (POSIX only). 137 138 .. attribute:: stdout 139 140 Captured stdout from the child process. A bytes sequence, or a string if 141 :func:`run` was called with an encoding, errors, or text=True. 142 ``None`` if stdout was not captured. 143 144 If you ran the process with ``stderr=subprocess.STDOUT``, stdout and 145 stderr will be combined in this attribute, and :attr:`stderr` will be 146 ``None``. 147 148 .. attribute:: stderr 149 150 Captured stderr from the child process. A bytes sequence, or a string if 151 :func:`run` was called with an encoding, errors, or text=True. 152 ``None`` if stderr was not captured. 153 154 .. method:: check_returncode() 155 156 If :attr:`returncode` is non-zero, raise a :exc:`CalledProcessError`. 157 158 .. versionadded:: 3.5 159 160.. data:: DEVNULL 161 162 Special value that can be used as the *stdin*, *stdout* or *stderr* argument 163 to :class:`Popen` and indicates that the special file :data:`os.devnull` 164 will be used. 165 166 .. versionadded:: 3.3 167 168 169.. data:: PIPE 170 171 Special value that can be used as the *stdin*, *stdout* or *stderr* argument 172 to :class:`Popen` and indicates that a pipe to the standard stream should be 173 opened. Most useful with :meth:`Popen.communicate`. 174 175 176.. data:: STDOUT 177 178 Special value that can be used as the *stderr* argument to :class:`Popen` and 179 indicates that standard error should go into the same handle as standard 180 output. 181 182 183.. exception:: SubprocessError 184 185 Base class for all other exceptions from this module. 186 187 .. versionadded:: 3.3 188 189 190.. exception:: TimeoutExpired 191 192 Subclass of :exc:`SubprocessError`, raised when a timeout expires 193 while waiting for a child process. 194 195 .. attribute:: cmd 196 197 Command that was used to spawn the child process. 198 199 .. attribute:: timeout 200 201 Timeout in seconds. 202 203 .. attribute:: output 204 205 Output of the child process if it was captured by :func:`run` or 206 :func:`check_output`. Otherwise, ``None``. This is always 207 :class:`bytes` when any output was captured regardless of the 208 ``text=True`` setting. It may remain ``None`` instead of ``b''`` 209 when no output was observed. 210 211 .. attribute:: stdout 212 213 Alias for output, for symmetry with :attr:`stderr`. 214 215 .. attribute:: stderr 216 217 Stderr output of the child process if it was captured by :func:`run`. 218 Otherwise, ``None``. This is always :class:`bytes` when stderr output 219 was captured regardless of the ``text=True`` setting. It may remain 220 ``None`` instead of ``b''`` when no stderr output was observed. 221 222 .. versionadded:: 3.3 223 224 .. versionchanged:: 3.5 225 *stdout* and *stderr* attributes added 226 227.. exception:: CalledProcessError 228 229 Subclass of :exc:`SubprocessError`, raised when a process run by 230 :func:`check_call`, :func:`check_output`, or :func:`run` (with ``check=True``) 231 returns a non-zero exit status. 232 233 234 .. attribute:: returncode 235 236 Exit status of the child process. If the process exited due to a 237 signal, this will be the negative signal number. 238 239 .. attribute:: cmd 240 241 Command that was used to spawn the child process. 242 243 .. attribute:: output 244 245 Output of the child process if it was captured by :func:`run` or 246 :func:`check_output`. Otherwise, ``None``. 247 248 .. attribute:: stdout 249 250 Alias for output, for symmetry with :attr:`stderr`. 251 252 .. attribute:: stderr 253 254 Stderr output of the child process if it was captured by :func:`run`. 255 Otherwise, ``None``. 256 257 .. versionchanged:: 3.5 258 *stdout* and *stderr* attributes added 259 260 261.. _frequently-used-arguments: 262 263Frequently Used Arguments 264^^^^^^^^^^^^^^^^^^^^^^^^^ 265 266To support a wide variety of use cases, the :class:`Popen` constructor (and 267the convenience functions) accept a large number of optional arguments. For 268most typical use cases, many of these arguments can be safely left at their 269default values. The arguments that are most commonly needed are: 270 271 *args* is required for all calls and should be a string, or a sequence of 272 program arguments. Providing a sequence of arguments is generally 273 preferred, as it allows the module to take care of any required escaping 274 and quoting of arguments (e.g. to permit spaces in file names). If passing 275 a single string, either *shell* must be :const:`True` (see below) or else 276 the string must simply name the program to be executed without specifying 277 any arguments. 278 279 *stdin*, *stdout* and *stderr* specify the executed program's standard input, 280 standard output and standard error file handles, respectively. Valid values 281 are :data:`PIPE`, :data:`DEVNULL`, an existing file descriptor (a positive 282 integer), an existing file object with a valid file descriptor, and ``None``. 283 :data:`PIPE` indicates that a new pipe to the child should be created. 284 :data:`DEVNULL` indicates that the special file :data:`os.devnull` will 285 be used. With the default settings of ``None``, no redirection will occur; 286 the child's file handles will be inherited from the parent. 287 Additionally, *stderr* can be :data:`STDOUT`, which indicates that the 288 stderr data from the child process should be captured into the same file 289 handle as for *stdout*. 290 291 .. index:: 292 single: universal newlines; subprocess module 293 294 If *encoding* or *errors* are specified, or *text* (also known as 295 *universal_newlines*) is true, 296 the file objects *stdin*, *stdout* and *stderr* will be opened in text 297 mode using the *encoding* and *errors* specified in the call or the 298 defaults for :class:`io.TextIOWrapper`. 299 300 For *stdin*, line ending characters ``'\n'`` in the input will be converted 301 to the default line separator :data:`os.linesep`. For *stdout* and *stderr*, 302 all line endings in the output will be converted to ``'\n'``. For more 303 information see the documentation of the :class:`io.TextIOWrapper` class 304 when the *newline* argument to its constructor is ``None``. 305 306 If text mode is not used, *stdin*, *stdout* and *stderr* will be opened as 307 binary streams. No encoding or line ending conversion is performed. 308 309 .. versionadded:: 3.6 310 Added *encoding* and *errors* parameters. 311 312 .. versionadded:: 3.7 313 Added the *text* parameter as an alias for *universal_newlines*. 314 315 .. note:: 316 317 The newlines attribute of the file objects :attr:`Popen.stdin`, 318 :attr:`Popen.stdout` and :attr:`Popen.stderr` are not updated by 319 the :meth:`Popen.communicate` method. 320 321 If *shell* is ``True``, the specified command will be executed through 322 the shell. This can be useful if you are using Python primarily for the 323 enhanced control flow it offers over most system shells and still want 324 convenient access to other shell features such as shell pipes, filename 325 wildcards, environment variable expansion, and expansion of ``~`` to a 326 user's home directory. However, note that Python itself offers 327 implementations of many shell-like features (in particular, :mod:`glob`, 328 :mod:`fnmatch`, :func:`os.walk`, :func:`os.path.expandvars`, 329 :func:`os.path.expanduser`, and :mod:`shutil`). 330 331 .. versionchanged:: 3.3 332 When *universal_newlines* is ``True``, the class uses the encoding 333 :func:`locale.getpreferredencoding(False) <locale.getpreferredencoding>` 334 instead of ``locale.getpreferredencoding()``. See the 335 :class:`io.TextIOWrapper` class for more information on this change. 336 337 .. note:: 338 339 Read the `Security Considerations`_ section before using ``shell=True``. 340 341These options, along with all of the other options, are described in more 342detail in the :class:`Popen` constructor documentation. 343 344 345Popen Constructor 346^^^^^^^^^^^^^^^^^ 347 348The underlying process creation and management in this module is handled by 349the :class:`Popen` class. It offers a lot of flexibility so that developers 350are able to handle the less common cases not covered by the convenience 351functions. 352 353 354.. class:: Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, \ 355 stderr=None, preexec_fn=None, close_fds=True, shell=False, \ 356 cwd=None, env=None, universal_newlines=None, \ 357 startupinfo=None, creationflags=0, restore_signals=True, \ 358 start_new_session=False, pass_fds=(), *, group=None, \ 359 extra_groups=None, user=None, umask=-1, \ 360 encoding=None, errors=None, text=None, pipesize=-1, \ 361 process_group=None) 362 363 Execute a child program in a new process. On POSIX, the class uses 364 :meth:`os.execvpe`-like behavior to execute the child program. On Windows, 365 the class uses the Windows ``CreateProcess()`` function. The arguments to 366 :class:`Popen` are as follows. 367 368 *args* should be a sequence of program arguments or else a single string 369 or :term:`path-like object`. 370 By default, the program to execute is the first item in *args* if *args* is 371 a sequence. If *args* is a string, the interpretation is 372 platform-dependent and described below. See the *shell* and *executable* 373 arguments for additional differences from the default behavior. Unless 374 otherwise stated, it is recommended to pass *args* as a sequence. 375 376 .. warning:: 377 378 For maximum reliability, use a fully qualified path for the executable. 379 To search for an unqualified name on :envvar:`PATH`, use 380 :meth:`shutil.which`. On all platforms, passing :data:`sys.executable` 381 is the recommended way to launch the current Python interpreter again, 382 and use the ``-m`` command-line format to launch an installed module. 383 384 Resolving the path of *executable* (or the first item of *args*) is 385 platform dependent. For POSIX, see :meth:`os.execvpe`, and note that 386 when resolving or searching for the executable path, *cwd* overrides the 387 current working directory and *env* can override the ``PATH`` 388 environment variable. For Windows, see the documentation of the 389 ``lpApplicationName`` and ``lpCommandLine`` parameters of WinAPI 390 ``CreateProcess``, and note that when resolving or searching for the 391 executable path with ``shell=False``, *cwd* does not override the 392 current working directory and *env* cannot override the ``PATH`` 393 environment variable. Using a full path avoids all of these variations. 394 395 An example of passing some arguments to an external program 396 as a sequence is:: 397 398 Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."]) 399 400 On POSIX, if *args* is a string, the string is interpreted as the name or 401 path of the program to execute. However, this can only be done if not 402 passing arguments to the program. 403 404 .. note:: 405 406 It may not be obvious how to break a shell command into a sequence of arguments, 407 especially in complex cases. :meth:`shlex.split` can illustrate how to 408 determine the correct tokenization for *args*:: 409 410 >>> import shlex, subprocess 411 >>> command_line = input() 412 /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'" 413 >>> args = shlex.split(command_line) 414 >>> print(args) 415 ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"] 416 >>> p = subprocess.Popen(args) # Success! 417 418 Note in particular that options (such as *-input*) and arguments (such 419 as *eggs.txt*) that are separated by whitespace in the shell go in separate 420 list elements, while arguments that need quoting or backslash escaping when 421 used in the shell (such as filenames containing spaces or the *echo* command 422 shown above) are single list elements. 423 424 On Windows, if *args* is a sequence, it will be converted to a string in a 425 manner described in :ref:`converting-argument-sequence`. This is because 426 the underlying ``CreateProcess()`` operates on strings. 427 428 .. versionchanged:: 3.6 429 *args* parameter accepts a :term:`path-like object` if *shell* is 430 ``False`` and a sequence containing path-like objects on POSIX. 431 432 .. versionchanged:: 3.8 433 *args* parameter accepts a :term:`path-like object` if *shell* is 434 ``False`` and a sequence containing bytes and path-like objects 435 on Windows. 436 437 The *shell* argument (which defaults to ``False``) specifies whether to use 438 the shell as the program to execute. If *shell* is ``True``, it is 439 recommended to pass *args* as a string rather than as a sequence. 440 441 On POSIX with ``shell=True``, the shell defaults to :file:`/bin/sh`. If 442 *args* is a string, the string specifies the command 443 to execute through the shell. This means that the string must be 444 formatted exactly as it would be when typed at the shell prompt. This 445 includes, for example, quoting or backslash escaping filenames with spaces in 446 them. If *args* is a sequence, the first item specifies the command string, and 447 any additional items will be treated as additional arguments to the shell 448 itself. That is to say, :class:`Popen` does the equivalent of:: 449 450 Popen(['/bin/sh', '-c', args[0], args[1], ...]) 451 452 On Windows with ``shell=True``, the :envvar:`COMSPEC` environment variable 453 specifies the default shell. The only time you need to specify 454 ``shell=True`` on Windows is when the command you wish to execute is built 455 into the shell (e.g. :command:`dir` or :command:`copy`). You do not need 456 ``shell=True`` to run a batch file or console-based executable. 457 458 .. note:: 459 460 Read the `Security Considerations`_ section before using ``shell=True``. 461 462 *bufsize* will be supplied as the corresponding argument to the 463 :func:`open` function when creating the stdin/stdout/stderr pipe 464 file objects: 465 466 - :const:`0` means unbuffered (read and write are one 467 system call and can return short) 468 - :const:`1` means line buffered 469 (only usable if ``text=True`` or ``universal_newlines=True``) 470 - any other positive value means use a buffer of approximately that 471 size 472 - negative bufsize (the default) means the system default of 473 io.DEFAULT_BUFFER_SIZE will be used. 474 475 .. versionchanged:: 3.3.1 476 *bufsize* now defaults to -1 to enable buffering by default to match the 477 behavior that most code expects. In versions prior to Python 3.2.4 and 478 3.3.1 it incorrectly defaulted to :const:`0` which was unbuffered 479 and allowed short reads. This was unintentional and did not match the 480 behavior of Python 2 as most code expected. 481 482 The *executable* argument specifies a replacement program to execute. It 483 is very seldom needed. When ``shell=False``, *executable* replaces the 484 program to execute specified by *args*. However, the original *args* is 485 still passed to the program. Most programs treat the program specified 486 by *args* as the command name, which can then be different from the program 487 actually executed. On POSIX, the *args* name 488 becomes the display name for the executable in utilities such as 489 :program:`ps`. If ``shell=True``, on POSIX the *executable* argument 490 specifies a replacement shell for the default :file:`/bin/sh`. 491 492 .. versionchanged:: 3.6 493 *executable* parameter accepts a :term:`path-like object` on POSIX. 494 495 .. versionchanged:: 3.8 496 *executable* parameter accepts a bytes and :term:`path-like object` 497 on Windows. 498 499 .. versionchanged:: 3.11.3 500 501 Changed Windows shell search order for ``shell=True``. The current 502 directory and ``%PATH%`` are replaced with ``%COMSPEC%`` and 503 ``%SystemRoot%\System32\cmd.exe``. As a result, dropping a 504 malicious program named ``cmd.exe`` into a current directory no 505 longer works. 506 507 *stdin*, *stdout* and *stderr* specify the executed program's standard input, 508 standard output and standard error file handles, respectively. Valid values 509 are :data:`PIPE`, :data:`DEVNULL`, an existing file descriptor (a positive 510 integer), an existing :term:`file object` with a valid file descriptor, 511 and ``None``. :data:`PIPE` indicates that a new pipe to the child should 512 be created. :data:`DEVNULL` indicates that the special file 513 :data:`os.devnull` will be used. With the default settings of ``None``, 514 no redirection will occur; the child's file handles will be inherited from 515 the parent. Additionally, *stderr* can be :data:`STDOUT`, which indicates 516 that the stderr data from the applications should be captured into the same 517 file handle as for stdout. 518 519 If *preexec_fn* is set to a callable object, this object will be called in the 520 child process just before the child is executed. 521 (POSIX only) 522 523 .. warning:: 524 525 The *preexec_fn* parameter is NOT SAFE to use in the presence of threads 526 in your application. The child process could deadlock before exec is 527 called. 528 529 .. note:: 530 531 If you need to modify the environment for the child use the *env* 532 parameter rather than doing it in a *preexec_fn*. 533 The *start_new_session* and *process_group* parameters should take the place of 534 code using *preexec_fn* to call :func:`os.setsid` or :func:`os.setpgid` in the child. 535 536 .. versionchanged:: 3.8 537 538 The *preexec_fn* parameter is no longer supported in subinterpreters. 539 The use of the parameter in a subinterpreter raises 540 :exc:`RuntimeError`. The new restriction may affect applications that 541 are deployed in mod_wsgi, uWSGI, and other embedded environments. 542 543 If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and 544 :const:`2` will be closed before the child process is executed. Otherwise 545 when *close_fds* is false, file descriptors obey their inheritable flag 546 as described in :ref:`fd_inheritance`. 547 548 On Windows, if *close_fds* is true then no handles will be inherited by the 549 child process unless explicitly passed in the ``handle_list`` element of 550 :attr:`STARTUPINFO.lpAttributeList`, or by standard handle redirection. 551 552 .. versionchanged:: 3.2 553 The default for *close_fds* was changed from :const:`False` to 554 what is described above. 555 556 .. versionchanged:: 3.7 557 On Windows the default for *close_fds* was changed from :const:`False` to 558 :const:`True` when redirecting the standard handles. It's now possible to 559 set *close_fds* to :const:`True` when redirecting the standard handles. 560 561 *pass_fds* is an optional sequence of file descriptors to keep open 562 between the parent and child. Providing any *pass_fds* forces 563 *close_fds* to be :const:`True`. (POSIX only) 564 565 .. versionchanged:: 3.2 566 The *pass_fds* parameter was added. 567 568 If *cwd* is not ``None``, the function changes the working directory to 569 *cwd* before executing the child. *cwd* can be a string, bytes or 570 :term:`path-like <path-like object>` object. On POSIX, the function 571 looks for *executable* (or for the first item in *args*) relative to *cwd* 572 if the executable path is a relative path. 573 574 .. versionchanged:: 3.6 575 *cwd* parameter accepts a :term:`path-like object` on POSIX. 576 577 .. versionchanged:: 3.7 578 *cwd* parameter accepts a :term:`path-like object` on Windows. 579 580 .. versionchanged:: 3.8 581 *cwd* parameter accepts a bytes object on Windows. 582 583 If *restore_signals* is true (the default) all signals that Python has set to 584 SIG_IGN are restored to SIG_DFL in the child process before the exec. 585 Currently this includes the SIGPIPE, SIGXFZ and SIGXFSZ signals. 586 (POSIX only) 587 588 .. versionchanged:: 3.2 589 *restore_signals* was added. 590 591 If *start_new_session* is true the ``setsid()`` system call will be made in the 592 child process prior to the execution of the subprocess. 593 594 .. availability:: POSIX 595 .. versionchanged:: 3.2 596 *start_new_session* was added. 597 598 If *process_group* is a non-negative integer, the ``setpgid(0, value)`` system call will 599 be made in the child process prior to the execution of the subprocess. 600 601 .. availability:: POSIX 602 .. versionchanged:: 3.11 603 *process_group* was added. 604 605 If *group* is not ``None``, the setregid() system call will be made in the 606 child process prior to the execution of the subprocess. If the provided 607 value is a string, it will be looked up via :func:`grp.getgrnam()` and 608 the value in ``gr_gid`` will be used. If the value is an integer, it 609 will be passed verbatim. (POSIX only) 610 611 .. availability:: POSIX 612 .. versionadded:: 3.9 613 614 If *extra_groups* is not ``None``, the setgroups() system call will be 615 made in the child process prior to the execution of the subprocess. 616 Strings provided in *extra_groups* will be looked up via 617 :func:`grp.getgrnam()` and the values in ``gr_gid`` will be used. 618 Integer values will be passed verbatim. (POSIX only) 619 620 .. availability:: POSIX 621 .. versionadded:: 3.9 622 623 If *user* is not ``None``, the setreuid() system call will be made in the 624 child process prior to the execution of the subprocess. If the provided 625 value is a string, it will be looked up via :func:`pwd.getpwnam()` and 626 the value in ``pw_uid`` will be used. If the value is an integer, it will 627 be passed verbatim. (POSIX only) 628 629 .. availability:: POSIX 630 .. versionadded:: 3.9 631 632 If *umask* is not negative, the umask() system call will be made in the 633 child process prior to the execution of the subprocess. 634 635 .. availability:: POSIX 636 .. versionadded:: 3.9 637 638 If *env* is not ``None``, it must be a mapping that defines the environment 639 variables for the new process; these are used instead of the default 640 behavior of inheriting the current process' environment. This mapping can be 641 str to str on any platform or bytes to bytes on POSIX platforms much like 642 :data:`os.environ` or :data:`os.environb`. 643 644 .. note:: 645 646 If specified, *env* must provide any variables required for the program to 647 execute. On Windows, in order to run a `side-by-side assembly`_ the 648 specified *env* **must** include a valid :envvar:`SystemRoot`. 649 650 .. _side-by-side assembly: https://en.wikipedia.org/wiki/Side-by-Side_Assembly 651 652 If *encoding* or *errors* are specified, or *text* is true, the file objects 653 *stdin*, *stdout* and *stderr* are opened in text mode with the specified 654 *encoding* and *errors*, as described above in :ref:`frequently-used-arguments`. 655 The *universal_newlines* argument is equivalent to *text* and is provided 656 for backwards compatibility. By default, file objects are opened in binary mode. 657 658 .. versionadded:: 3.6 659 *encoding* and *errors* were added. 660 661 .. versionadded:: 3.7 662 *text* was added as a more readable alias for *universal_newlines*. 663 664 If given, *startupinfo* will be a :class:`STARTUPINFO` object, which is 665 passed to the underlying ``CreateProcess`` function. 666 *creationflags*, if given, can be one or more of the following flags: 667 668 * :data:`CREATE_NEW_CONSOLE` 669 * :data:`CREATE_NEW_PROCESS_GROUP` 670 * :data:`ABOVE_NORMAL_PRIORITY_CLASS` 671 * :data:`BELOW_NORMAL_PRIORITY_CLASS` 672 * :data:`HIGH_PRIORITY_CLASS` 673 * :data:`IDLE_PRIORITY_CLASS` 674 * :data:`NORMAL_PRIORITY_CLASS` 675 * :data:`REALTIME_PRIORITY_CLASS` 676 * :data:`CREATE_NO_WINDOW` 677 * :data:`DETACHED_PROCESS` 678 * :data:`CREATE_DEFAULT_ERROR_MODE` 679 * :data:`CREATE_BREAKAWAY_FROM_JOB` 680 681 *pipesize* can be used to change the size of the pipe when 682 :data:`PIPE` is used for *stdin*, *stdout* or *stderr*. The size of the pipe 683 is only changed on platforms that support this (only Linux at this time of 684 writing). Other platforms will ignore this parameter. 685 686 .. versionadded:: 3.10 687 The ``pipesize`` parameter was added. 688 689 Popen objects are supported as context managers via the :keyword:`with` statement: 690 on exit, standard file descriptors are closed, and the process is waited for. 691 :: 692 693 with Popen(["ifconfig"], stdout=PIPE) as proc: 694 log.write(proc.stdout.read()) 695 696 .. audit-event:: subprocess.Popen executable,args,cwd,env subprocess.Popen 697 698 Popen and the other functions in this module that use it raise an 699 :ref:`auditing event <auditing>` ``subprocess.Popen`` with arguments 700 ``executable``, ``args``, ``cwd``, and ``env``. The value for ``args`` 701 may be a single string or a list of strings, depending on platform. 702 703 .. versionchanged:: 3.2 704 Added context manager support. 705 706 .. versionchanged:: 3.6 707 Popen destructor now emits a :exc:`ResourceWarning` warning if the child 708 process is still running. 709 710 .. versionchanged:: 3.8 711 Popen can use :func:`os.posix_spawn` in some cases for better 712 performance. On Windows Subsystem for Linux and QEMU User Emulation, 713 Popen constructor using :func:`os.posix_spawn` no longer raise an 714 exception on errors like missing program, but the child process fails 715 with a non-zero :attr:`~Popen.returncode`. 716 717 718Exceptions 719^^^^^^^^^^ 720 721Exceptions raised in the child process, before the new program has started to 722execute, will be re-raised in the parent. 723 724The most common exception raised is :exc:`OSError`. This occurs, for example, 725when trying to execute a non-existent file. Applications should prepare for 726:exc:`OSError` exceptions. Note that, when ``shell=True``, :exc:`OSError` 727will be raised by the child only if the selected shell itself was not found. 728To determine if the shell failed to find the requested application, it is 729necessary to check the return code or output from the subprocess. 730 731A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid 732arguments. 733 734:func:`check_call` and :func:`check_output` will raise 735:exc:`CalledProcessError` if the called process returns a non-zero return 736code. 737 738All of the functions and methods that accept a *timeout* parameter, such as 739:func:`call` and :meth:`Popen.communicate` will raise :exc:`TimeoutExpired` if 740the timeout expires before the process exits. 741 742Exceptions defined in this module all inherit from :exc:`SubprocessError`. 743 744 .. versionadded:: 3.3 745 The :exc:`SubprocessError` base class was added. 746 747.. _subprocess-security: 748 749Security Considerations 750----------------------- 751 752Unlike some other popen functions, this implementation will never 753implicitly call a system shell. This means that all characters, 754including shell metacharacters, can safely be passed to child processes. 755If the shell is invoked explicitly, via ``shell=True``, it is the application's 756responsibility to ensure that all whitespace and metacharacters are 757quoted appropriately to avoid 758`shell injection <https://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_ 759vulnerabilities. On :ref:`some platforms <shlex-quote-warning>`, it is possible 760to use :func:`shlex.quote` for this escaping. 761 762 763Popen Objects 764------------- 765 766Instances of the :class:`Popen` class have the following methods: 767 768 769.. method:: Popen.poll() 770 771 Check if child process has terminated. Set and return 772 :attr:`~Popen.returncode` attribute. Otherwise, returns ``None``. 773 774 775.. method:: Popen.wait(timeout=None) 776 777 Wait for child process to terminate. Set and return 778 :attr:`~Popen.returncode` attribute. 779 780 If the process does not terminate after *timeout* seconds, raise a 781 :exc:`TimeoutExpired` exception. It is safe to catch this exception and 782 retry the wait. 783 784 .. note:: 785 786 This will deadlock when using ``stdout=PIPE`` or ``stderr=PIPE`` 787 and the child process generates enough output to a pipe such that 788 it blocks waiting for the OS pipe buffer to accept more data. 789 Use :meth:`Popen.communicate` when using pipes to avoid that. 790 791 .. note:: 792 793 The function is implemented using a busy loop (non-blocking call and 794 short sleeps). Use the :mod:`asyncio` module for an asynchronous wait: 795 see :class:`asyncio.create_subprocess_exec`. 796 797 .. versionchanged:: 3.3 798 *timeout* was added. 799 800.. method:: Popen.communicate(input=None, timeout=None) 801 802 Interact with process: Send data to stdin. Read data from stdout and stderr, 803 until end-of-file is reached. Wait for process to terminate and set the 804 :attr:`~Popen.returncode` attribute. The optional *input* argument should be 805 data to be sent to the child process, or ``None``, if no data should be sent 806 to the child. If streams were opened in text mode, *input* must be a string. 807 Otherwise, it must be bytes. 808 809 :meth:`communicate` returns a tuple ``(stdout_data, stderr_data)``. 810 The data will be strings if streams were opened in text mode; otherwise, 811 bytes. 812 813 Note that if you want to send data to the process's stdin, you need to create 814 the Popen object with ``stdin=PIPE``. Similarly, to get anything other than 815 ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or 816 ``stderr=PIPE`` too. 817 818 If the process does not terminate after *timeout* seconds, a 819 :exc:`TimeoutExpired` exception will be raised. Catching this exception and 820 retrying communication will not lose any output. 821 822 The child process is not killed if the timeout expires, so in order to 823 cleanup properly a well-behaved application should kill the child process and 824 finish communication:: 825 826 proc = subprocess.Popen(...) 827 try: 828 outs, errs = proc.communicate(timeout=15) 829 except TimeoutExpired: 830 proc.kill() 831 outs, errs = proc.communicate() 832 833 .. note:: 834 835 The data read is buffered in memory, so do not use this method if the data 836 size is large or unlimited. 837 838 .. versionchanged:: 3.3 839 *timeout* was added. 840 841 842.. method:: Popen.send_signal(signal) 843 844 Sends the signal *signal* to the child. 845 846 Do nothing if the process completed. 847 848 .. note:: 849 850 On Windows, SIGTERM is an alias for :meth:`terminate`. CTRL_C_EVENT and 851 CTRL_BREAK_EVENT can be sent to processes started with a *creationflags* 852 parameter which includes ``CREATE_NEW_PROCESS_GROUP``. 853 854 855.. method:: Popen.terminate() 856 857 Stop the child. On POSIX OSs the method sends SIGTERM to the 858 child. On Windows the Win32 API function :c:func:`TerminateProcess` is called 859 to stop the child. 860 861 862.. method:: Popen.kill() 863 864 Kills the child. On POSIX OSs the function sends SIGKILL to the child. 865 On Windows :meth:`kill` is an alias for :meth:`terminate`. 866 867 868The following attributes are also set by the class for you to access. 869Reassigning them to new values is unsupported: 870 871.. attribute:: Popen.args 872 873 The *args* argument as it was passed to :class:`Popen` -- a 874 sequence of program arguments or else a single string. 875 876 .. versionadded:: 3.3 877 878.. attribute:: Popen.stdin 879 880 If the *stdin* argument was :data:`PIPE`, this attribute is a writeable 881 stream object as returned by :func:`open`. If the *encoding* or *errors* 882 arguments were specified or the *text* or *universal_newlines* argument 883 was ``True``, the stream is a text stream, otherwise it is a byte stream. 884 If the *stdin* argument was not :data:`PIPE`, this attribute is ``None``. 885 886 887.. attribute:: Popen.stdout 888 889 If the *stdout* argument was :data:`PIPE`, this attribute is a readable 890 stream object as returned by :func:`open`. Reading from the stream provides 891 output from the child process. If the *encoding* or *errors* arguments were 892 specified or the *text* or *universal_newlines* argument was ``True``, the 893 stream is a text stream, otherwise it is a byte stream. If the *stdout* 894 argument was not :data:`PIPE`, this attribute is ``None``. 895 896 897.. attribute:: Popen.stderr 898 899 If the *stderr* argument was :data:`PIPE`, this attribute is a readable 900 stream object as returned by :func:`open`. Reading from the stream provides 901 error output from the child process. If the *encoding* or *errors* arguments 902 were specified or the *text* or *universal_newlines* argument was ``True``, the 903 stream is a text stream, otherwise it is a byte stream. If the *stderr* argument 904 was not :data:`PIPE`, this attribute is ``None``. 905 906.. warning:: 907 908 Use :meth:`~Popen.communicate` rather than :attr:`.stdin.write <Popen.stdin>`, 909 :attr:`.stdout.read <Popen.stdout>` or :attr:`.stderr.read <Popen.stderr>` to avoid 910 deadlocks due to any of the other OS pipe buffers filling up and blocking the 911 child process. 912 913 914.. attribute:: Popen.pid 915 916 The process ID of the child process. 917 918 Note that if you set the *shell* argument to ``True``, this is the process ID 919 of the spawned shell. 920 921 922.. attribute:: Popen.returncode 923 924 The child return code. Initially ``None``, :attr:`returncode` is set by 925 a call to the :meth:`poll`, :meth:`wait`, or :meth:`communicate` methods 926 if they detect that the process has terminated. 927 928 A ``None`` value indicates that the process hadn't yet terminated at the 929 time of the last method call. 930 931 A negative value ``-N`` indicates that the child was terminated by signal 932 ``N`` (POSIX only). 933 934 935Windows Popen Helpers 936--------------------- 937 938The :class:`STARTUPINFO` class and following constants are only available 939on Windows. 940 941.. class:: STARTUPINFO(*, dwFlags=0, hStdInput=None, hStdOutput=None, \ 942 hStdError=None, wShowWindow=0, lpAttributeList=None) 943 944 Partial support of the Windows 945 `STARTUPINFO <https://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx>`__ 946 structure is used for :class:`Popen` creation. The following attributes can 947 be set by passing them as keyword-only arguments. 948 949 .. versionchanged:: 3.7 950 Keyword-only argument support was added. 951 952 .. attribute:: dwFlags 953 954 A bit field that determines whether certain :class:`STARTUPINFO` 955 attributes are used when the process creates a window. :: 956 957 si = subprocess.STARTUPINFO() 958 si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW 959 960 .. attribute:: hStdInput 961 962 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute 963 is the standard input handle for the process. If 964 :data:`STARTF_USESTDHANDLES` is not specified, the default for standard 965 input is the keyboard buffer. 966 967 .. attribute:: hStdOutput 968 969 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute 970 is the standard output handle for the process. Otherwise, this attribute 971 is ignored and the default for standard output is the console window's 972 buffer. 973 974 .. attribute:: hStdError 975 976 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute 977 is the standard error handle for the process. Otherwise, this attribute is 978 ignored and the default for standard error is the console window's buffer. 979 980 .. attribute:: wShowWindow 981 982 If :attr:`dwFlags` specifies :data:`STARTF_USESHOWWINDOW`, this attribute 983 can be any of the values that can be specified in the ``nCmdShow`` 984 parameter for the 985 `ShowWindow <https://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx>`__ 986 function, except for ``SW_SHOWDEFAULT``. Otherwise, this attribute is 987 ignored. 988 989 :data:`SW_HIDE` is provided for this attribute. It is used when 990 :class:`Popen` is called with ``shell=True``. 991 992 .. attribute:: lpAttributeList 993 994 A dictionary of additional attributes for process creation as given in 995 ``STARTUPINFOEX``, see 996 `UpdateProcThreadAttribute <https://msdn.microsoft.com/en-us/library/windows/desktop/ms686880(v=vs.85).aspx>`__. 997 998 Supported attributes: 999 1000 **handle_list** 1001 Sequence of handles that will be inherited. *close_fds* must be true if 1002 non-empty. 1003 1004 The handles must be temporarily made inheritable by 1005 :func:`os.set_handle_inheritable` when passed to the :class:`Popen` 1006 constructor, else :class:`OSError` will be raised with Windows error 1007 ``ERROR_INVALID_PARAMETER`` (87). 1008 1009 .. warning:: 1010 1011 In a multithreaded process, use caution to avoid leaking handles 1012 that are marked inheritable when combining this feature with 1013 concurrent calls to other process creation functions that inherit 1014 all handles such as :func:`os.system`. This also applies to 1015 standard handle redirection, which temporarily creates inheritable 1016 handles. 1017 1018 .. versionadded:: 3.7 1019 1020Windows Constants 1021^^^^^^^^^^^^^^^^^ 1022 1023The :mod:`subprocess` module exposes the following constants. 1024 1025.. data:: STD_INPUT_HANDLE 1026 1027 The standard input device. Initially, this is the console input buffer, 1028 ``CONIN$``. 1029 1030.. data:: STD_OUTPUT_HANDLE 1031 1032 The standard output device. Initially, this is the active console screen 1033 buffer, ``CONOUT$``. 1034 1035.. data:: STD_ERROR_HANDLE 1036 1037 The standard error device. Initially, this is the active console screen 1038 buffer, ``CONOUT$``. 1039 1040.. data:: SW_HIDE 1041 1042 Hides the window. Another window will be activated. 1043 1044.. data:: STARTF_USESTDHANDLES 1045 1046 Specifies that the :attr:`STARTUPINFO.hStdInput`, 1047 :attr:`STARTUPINFO.hStdOutput`, and :attr:`STARTUPINFO.hStdError` attributes 1048 contain additional information. 1049 1050.. data:: STARTF_USESHOWWINDOW 1051 1052 Specifies that the :attr:`STARTUPINFO.wShowWindow` attribute contains 1053 additional information. 1054 1055.. data:: CREATE_NEW_CONSOLE 1056 1057 The new process has a new console, instead of inheriting its parent's 1058 console (the default). 1059 1060.. data:: CREATE_NEW_PROCESS_GROUP 1061 1062 A :class:`Popen` ``creationflags`` parameter to specify that a new process 1063 group will be created. This flag is necessary for using :func:`os.kill` 1064 on the subprocess. 1065 1066 This flag is ignored if :data:`CREATE_NEW_CONSOLE` is specified. 1067 1068.. data:: ABOVE_NORMAL_PRIORITY_CLASS 1069 1070 A :class:`Popen` ``creationflags`` parameter to specify that a new process 1071 will have an above average priority. 1072 1073 .. versionadded:: 3.7 1074 1075.. data:: BELOW_NORMAL_PRIORITY_CLASS 1076 1077 A :class:`Popen` ``creationflags`` parameter to specify that a new process 1078 will have a below average priority. 1079 1080 .. versionadded:: 3.7 1081 1082.. data:: HIGH_PRIORITY_CLASS 1083 1084 A :class:`Popen` ``creationflags`` parameter to specify that a new process 1085 will have a high priority. 1086 1087 .. versionadded:: 3.7 1088 1089.. data:: IDLE_PRIORITY_CLASS 1090 1091 A :class:`Popen` ``creationflags`` parameter to specify that a new process 1092 will have an idle (lowest) priority. 1093 1094 .. versionadded:: 3.7 1095 1096.. data:: NORMAL_PRIORITY_CLASS 1097 1098 A :class:`Popen` ``creationflags`` parameter to specify that a new process 1099 will have an normal priority. (default) 1100 1101 .. versionadded:: 3.7 1102 1103.. data:: REALTIME_PRIORITY_CLASS 1104 1105 A :class:`Popen` ``creationflags`` parameter to specify that a new process 1106 will have realtime priority. 1107 You should almost never use REALTIME_PRIORITY_CLASS, because this interrupts 1108 system threads that manage mouse input, keyboard input, and background disk 1109 flushing. This class can be appropriate for applications that "talk" directly 1110 to hardware or that perform brief tasks that should have limited interruptions. 1111 1112 .. versionadded:: 3.7 1113 1114.. data:: CREATE_NO_WINDOW 1115 1116 A :class:`Popen` ``creationflags`` parameter to specify that a new process 1117 will not create a window. 1118 1119 .. versionadded:: 3.7 1120 1121.. data:: DETACHED_PROCESS 1122 1123 A :class:`Popen` ``creationflags`` parameter to specify that a new process 1124 will not inherit its parent's console. 1125 This value cannot be used with CREATE_NEW_CONSOLE. 1126 1127 .. versionadded:: 3.7 1128 1129.. data:: CREATE_DEFAULT_ERROR_MODE 1130 1131 A :class:`Popen` ``creationflags`` parameter to specify that a new process 1132 does not inherit the error mode of the calling process. Instead, the new 1133 process gets the default error mode. 1134 This feature is particularly useful for multithreaded shell applications 1135 that run with hard errors disabled. 1136 1137 .. versionadded:: 3.7 1138 1139.. data:: CREATE_BREAKAWAY_FROM_JOB 1140 1141 A :class:`Popen` ``creationflags`` parameter to specify that a new process 1142 is not associated with the job. 1143 1144 .. versionadded:: 3.7 1145 1146.. _call-function-trio: 1147 1148Older high-level API 1149-------------------- 1150 1151Prior to Python 3.5, these three functions comprised the high level API to 1152subprocess. You can now use :func:`run` in many cases, but lots of existing code 1153calls these functions. 1154 1155.. function:: call(args, *, stdin=None, stdout=None, stderr=None, \ 1156 shell=False, cwd=None, timeout=None, **other_popen_kwargs) 1157 1158 Run the command described by *args*. Wait for command to complete, then 1159 return the :attr:`~Popen.returncode` attribute. 1160 1161 Code needing to capture stdout or stderr should use :func:`run` instead:: 1162 1163 run(...).returncode 1164 1165 To suppress stdout or stderr, supply a value of :data:`DEVNULL`. 1166 1167 The arguments shown above are merely some common ones. 1168 The full function signature is the 1169 same as that of the :class:`Popen` constructor - this function passes all 1170 supplied arguments other than *timeout* directly through to that interface. 1171 1172 .. note:: 1173 1174 Do not use ``stdout=PIPE`` or ``stderr=PIPE`` with this 1175 function. The child process will block if it generates enough 1176 output to a pipe to fill up the OS pipe buffer as the pipes are 1177 not being read from. 1178 1179 .. versionchanged:: 3.3 1180 *timeout* was added. 1181 1182 .. versionchanged:: 3.11.3 1183 1184 Changed Windows shell search order for ``shell=True``. The current 1185 directory and ``%PATH%`` are replaced with ``%COMSPEC%`` and 1186 ``%SystemRoot%\System32\cmd.exe``. As a result, dropping a 1187 malicious program named ``cmd.exe`` into a current directory no 1188 longer works. 1189 1190.. function:: check_call(args, *, stdin=None, stdout=None, stderr=None, \ 1191 shell=False, cwd=None, timeout=None, \ 1192 **other_popen_kwargs) 1193 1194 Run command with arguments. Wait for command to complete. If the return 1195 code was zero then return, otherwise raise :exc:`CalledProcessError`. The 1196 :exc:`CalledProcessError` object will have the return code in the 1197 :attr:`~CalledProcessError.returncode` attribute. 1198 If :func:`check_call` was unable to start the process it will propagate the exception 1199 that was raised. 1200 1201 Code needing to capture stdout or stderr should use :func:`run` instead:: 1202 1203 run(..., check=True) 1204 1205 To suppress stdout or stderr, supply a value of :data:`DEVNULL`. 1206 1207 The arguments shown above are merely some common ones. 1208 The full function signature is the 1209 same as that of the :class:`Popen` constructor - this function passes all 1210 supplied arguments other than *timeout* directly through to that interface. 1211 1212 .. note:: 1213 1214 Do not use ``stdout=PIPE`` or ``stderr=PIPE`` with this 1215 function. The child process will block if it generates enough 1216 output to a pipe to fill up the OS pipe buffer as the pipes are 1217 not being read from. 1218 1219 .. versionchanged:: 3.3 1220 *timeout* was added. 1221 1222 .. versionchanged:: 3.11.3 1223 1224 Changed Windows shell search order for ``shell=True``. The current 1225 directory and ``%PATH%`` are replaced with ``%COMSPEC%`` and 1226 ``%SystemRoot%\System32\cmd.exe``. As a result, dropping a 1227 malicious program named ``cmd.exe`` into a current directory no 1228 longer works. 1229 1230 1231.. function:: check_output(args, *, stdin=None, stderr=None, shell=False, \ 1232 cwd=None, encoding=None, errors=None, \ 1233 universal_newlines=None, timeout=None, text=None, \ 1234 **other_popen_kwargs) 1235 1236 Run command with arguments and return its output. 1237 1238 If the return code was non-zero it raises a :exc:`CalledProcessError`. The 1239 :exc:`CalledProcessError` object will have the return code in the 1240 :attr:`~CalledProcessError.returncode` attribute and any output in the 1241 :attr:`~CalledProcessError.output` attribute. 1242 1243 This is equivalent to:: 1244 1245 run(..., check=True, stdout=PIPE).stdout 1246 1247 The arguments shown above are merely some common ones. 1248 The full function signature is largely the same as that of :func:`run` - 1249 most arguments are passed directly through to that interface. 1250 One API deviation from :func:`run` behavior exists: passing ``input=None`` 1251 will behave the same as ``input=b''`` (or ``input=''``, depending on other 1252 arguments) rather than using the parent's standard input file handle. 1253 1254 By default, this function will return the data as encoded bytes. The actual 1255 encoding of the output data may depend on the command being invoked, so the 1256 decoding to text will often need to be handled at the application level. 1257 1258 This behaviour may be overridden by setting *text*, *encoding*, *errors*, 1259 or *universal_newlines* to ``True`` as described in 1260 :ref:`frequently-used-arguments` and :func:`run`. 1261 1262 To also capture standard error in the result, use 1263 ``stderr=subprocess.STDOUT``:: 1264 1265 >>> subprocess.check_output( 1266 ... "ls non_existent_file; exit 0", 1267 ... stderr=subprocess.STDOUT, 1268 ... shell=True) 1269 'ls: non_existent_file: No such file or directory\n' 1270 1271 .. versionadded:: 3.1 1272 1273 .. versionchanged:: 3.3 1274 *timeout* was added. 1275 1276 .. versionchanged:: 3.4 1277 Support for the *input* keyword argument was added. 1278 1279 .. versionchanged:: 3.6 1280 *encoding* and *errors* were added. See :func:`run` for details. 1281 1282 .. versionadded:: 3.7 1283 *text* was added as a more readable alias for *universal_newlines*. 1284 1285 .. versionchanged:: 3.11.3 1286 1287 Changed Windows shell search order for ``shell=True``. The current 1288 directory and ``%PATH%`` are replaced with ``%COMSPEC%`` and 1289 ``%SystemRoot%\System32\cmd.exe``. As a result, dropping a 1290 malicious program named ``cmd.exe`` into a current directory no 1291 longer works. 1292 1293 1294.. _subprocess-replacements: 1295 1296Replacing Older Functions with the :mod:`subprocess` Module 1297----------------------------------------------------------- 1298 1299In this section, "a becomes b" means that b can be used as a replacement for a. 1300 1301.. note:: 1302 1303 All "a" functions in this section fail (more or less) silently if the 1304 executed program cannot be found; the "b" replacements raise :exc:`OSError` 1305 instead. 1306 1307 In addition, the replacements using :func:`check_output` will fail with a 1308 :exc:`CalledProcessError` if the requested operation produces a non-zero 1309 return code. The output is still available as the 1310 :attr:`~CalledProcessError.output` attribute of the raised exception. 1311 1312In the following examples, we assume that the relevant functions have already 1313been imported from the :mod:`subprocess` module. 1314 1315 1316Replacing :program:`/bin/sh` shell command substitution 1317^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1318 1319.. code-block:: bash 1320 1321 output=$(mycmd myarg) 1322 1323becomes:: 1324 1325 output = check_output(["mycmd", "myarg"]) 1326 1327Replacing shell pipeline 1328^^^^^^^^^^^^^^^^^^^^^^^^ 1329 1330.. code-block:: bash 1331 1332 output=$(dmesg | grep hda) 1333 1334becomes:: 1335 1336 p1 = Popen(["dmesg"], stdout=PIPE) 1337 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) 1338 p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. 1339 output = p2.communicate()[0] 1340 1341The ``p1.stdout.close()`` call after starting the p2 is important in order for 1342p1 to receive a SIGPIPE if p2 exits before p1. 1343 1344Alternatively, for trusted input, the shell's own pipeline support may still 1345be used directly: 1346 1347.. code-block:: bash 1348 1349 output=$(dmesg | grep hda) 1350 1351becomes:: 1352 1353 output = check_output("dmesg | grep hda", shell=True) 1354 1355 1356Replacing :func:`os.system` 1357^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1358 1359:: 1360 1361 sts = os.system("mycmd" + " myarg") 1362 # becomes 1363 retcode = call("mycmd" + " myarg", shell=True) 1364 1365Notes: 1366 1367* Calling the program through the shell is usually not required. 1368* The :func:`call` return value is encoded differently to that of 1369 :func:`os.system`. 1370 1371* The :func:`os.system` function ignores SIGINT and SIGQUIT signals while 1372 the command is running, but the caller must do this separately when 1373 using the :mod:`subprocess` module. 1374 1375A more realistic example would look like this:: 1376 1377 try: 1378 retcode = call("mycmd" + " myarg", shell=True) 1379 if retcode < 0: 1380 print("Child was terminated by signal", -retcode, file=sys.stderr) 1381 else: 1382 print("Child returned", retcode, file=sys.stderr) 1383 except OSError as e: 1384 print("Execution failed:", e, file=sys.stderr) 1385 1386 1387Replacing the :func:`os.spawn <os.spawnl>` family 1388^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1389 1390P_NOWAIT example:: 1391 1392 pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") 1393 ==> 1394 pid = Popen(["/bin/mycmd", "myarg"]).pid 1395 1396P_WAIT example:: 1397 1398 retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg") 1399 ==> 1400 retcode = call(["/bin/mycmd", "myarg"]) 1401 1402Vector example:: 1403 1404 os.spawnvp(os.P_NOWAIT, path, args) 1405 ==> 1406 Popen([path] + args[1:]) 1407 1408Environment example:: 1409 1410 os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env) 1411 ==> 1412 Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}) 1413 1414 1415 1416Replacing :func:`os.popen`, :func:`os.popen2`, :func:`os.popen3` 1417^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1418 1419:: 1420 1421 (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize) 1422 ==> 1423 p = Popen(cmd, shell=True, bufsize=bufsize, 1424 stdin=PIPE, stdout=PIPE, close_fds=True) 1425 (child_stdin, child_stdout) = (p.stdin, p.stdout) 1426 1427:: 1428 1429 (child_stdin, 1430 child_stdout, 1431 child_stderr) = os.popen3(cmd, mode, bufsize) 1432 ==> 1433 p = Popen(cmd, shell=True, bufsize=bufsize, 1434 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) 1435 (child_stdin, 1436 child_stdout, 1437 child_stderr) = (p.stdin, p.stdout, p.stderr) 1438 1439:: 1440 1441 (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize) 1442 ==> 1443 p = Popen(cmd, shell=True, bufsize=bufsize, 1444 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) 1445 (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout) 1446 1447Return code handling translates as follows:: 1448 1449 pipe = os.popen(cmd, 'w') 1450 ... 1451 rc = pipe.close() 1452 if rc is not None and rc >> 8: 1453 print("There were some errors") 1454 ==> 1455 process = Popen(cmd, stdin=PIPE) 1456 ... 1457 process.stdin.close() 1458 if process.wait() != 0: 1459 print("There were some errors") 1460 1461 1462Replacing functions from the :mod:`popen2` module 1463^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1464 1465.. note:: 1466 1467 If the cmd argument to popen2 functions is a string, the command is executed 1468 through /bin/sh. If it is a list, the command is directly executed. 1469 1470:: 1471 1472 (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode) 1473 ==> 1474 p = Popen("somestring", shell=True, bufsize=bufsize, 1475 stdin=PIPE, stdout=PIPE, close_fds=True) 1476 (child_stdout, child_stdin) = (p.stdout, p.stdin) 1477 1478:: 1479 1480 (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode) 1481 ==> 1482 p = Popen(["mycmd", "myarg"], bufsize=bufsize, 1483 stdin=PIPE, stdout=PIPE, close_fds=True) 1484 (child_stdout, child_stdin) = (p.stdout, p.stdin) 1485 1486:class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as 1487:class:`subprocess.Popen`, except that: 1488 1489* :class:`Popen` raises an exception if the execution fails. 1490 1491* The *capturestderr* argument is replaced with the *stderr* argument. 1492 1493* ``stdin=PIPE`` and ``stdout=PIPE`` must be specified. 1494 1495* popen2 closes all file descriptors by default, but you have to specify 1496 ``close_fds=True`` with :class:`Popen` to guarantee this behavior on 1497 all platforms or past Python versions. 1498 1499 1500Legacy Shell Invocation Functions 1501--------------------------------- 1502 1503This module also provides the following legacy functions from the 2.x 1504``commands`` module. These operations implicitly invoke the system shell and 1505none of the guarantees described above regarding security and exception 1506handling consistency are valid for these functions. 1507 1508.. function:: getstatusoutput(cmd, *, encoding=None, errors=None) 1509 1510 Return ``(exitcode, output)`` of executing *cmd* in a shell. 1511 1512 Execute the string *cmd* in a shell with :meth:`Popen.check_output` and 1513 return a 2-tuple ``(exitcode, output)``. 1514 *encoding* and *errors* are used to decode output; 1515 see the notes on :ref:`frequently-used-arguments` for more details. 1516 1517 A trailing newline is stripped from the output. 1518 The exit code for the command can be interpreted as the return code 1519 of subprocess. Example:: 1520 1521 >>> subprocess.getstatusoutput('ls /bin/ls') 1522 (0, '/bin/ls') 1523 >>> subprocess.getstatusoutput('cat /bin/junk') 1524 (1, 'cat: /bin/junk: No such file or directory') 1525 >>> subprocess.getstatusoutput('/bin/junk') 1526 (127, 'sh: /bin/junk: not found') 1527 >>> subprocess.getstatusoutput('/bin/kill $$') 1528 (-15, '') 1529 1530 .. availability:: Unix, Windows. 1531 1532 .. versionchanged:: 3.3.4 1533 Windows support was added. 1534 1535 The function now returns (exitcode, output) instead of (status, output) 1536 as it did in Python 3.3.3 and earlier. exitcode has the same value as 1537 :attr:`~Popen.returncode`. 1538 1539 .. versionadded:: 3.11 1540 Added *encoding* and *errors* arguments. 1541 1542.. function:: getoutput(cmd, *, encoding=None, errors=None) 1543 1544 Return output (stdout and stderr) of executing *cmd* in a shell. 1545 1546 Like :func:`getstatusoutput`, except the exit code is ignored and the return 1547 value is a string containing the command's output. Example:: 1548 1549 >>> subprocess.getoutput('ls /bin/ls') 1550 '/bin/ls' 1551 1552 .. availability:: Unix, Windows. 1553 1554 .. versionchanged:: 3.3.4 1555 Windows support added 1556 1557 .. versionadded:: 3.11 1558 Added *encoding* and *errors* arguments. 1559 1560 1561Notes 1562----- 1563 1564.. _converting-argument-sequence: 1565 1566Converting an argument sequence to a string on Windows 1567^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1568 1569On Windows, an *args* sequence is converted to a string that can be parsed 1570using the following rules (which correspond to the rules used by the MS C 1571runtime): 1572 15731. Arguments are delimited by white space, which is either a 1574 space or a tab. 1575 15762. A string surrounded by double quotation marks is 1577 interpreted as a single argument, regardless of white space 1578 contained within. A quoted string can be embedded in an 1579 argument. 1580 15813. A double quotation mark preceded by a backslash is 1582 interpreted as a literal double quotation mark. 1583 15844. Backslashes are interpreted literally, unless they 1585 immediately precede a double quotation mark. 1586 15875. If backslashes immediately precede a double quotation mark, 1588 every pair of backslashes is interpreted as a literal 1589 backslash. If the number of backslashes is odd, the last 1590 backslash escapes the next double quotation mark as 1591 described in rule 3. 1592 1593 1594.. seealso:: 1595 1596 :mod:`shlex` 1597 Module which provides function to parse and escape command lines. 1598 1599 1600.. _disable_vfork: 1601.. _disable_posix_spawn: 1602 1603Disabling use of ``vfork()`` or ``posix_spawn()`` 1604^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1605 1606On Linux, :mod:`subprocess` defaults to using the ``vfork()`` system call 1607internally when it is safe to do so rather than ``fork()``. This greatly 1608improves performance. 1609 1610If you ever encounter a presumed highly unusual situation where you need to 1611prevent ``vfork()`` from being used by Python, you can set the 1612:attr:`subprocess._USE_VFORK` attribute to a false value. 1613 1614:: 1615 1616 subprocess._USE_VFORK = False # See CPython issue gh-NNNNNN. 1617 1618Setting this has no impact on use of ``posix_spawn()`` which could use 1619``vfork()`` internally within its libc implementation. There is a similar 1620:attr:`subprocess._USE_POSIX_SPAWN` attribute if you need to prevent use of 1621that. 1622 1623:: 1624 1625 subprocess._USE_POSIX_SPAWN = False # See CPython issue gh-NNNNNN. 1626 1627It is safe to set these to false on any Python version. They will have no 1628effect on older versions when unsupported. Do not assume the attributes are 1629available to read. Despite their names, a true value does not indicate that the 1630corresponding function will be used, only that it may be. 1631 1632Please file issues any time you have to use these private knobs with a way to 1633reproduce the issue you were seeing. Link to that issue from a comment in your 1634code. 1635 1636.. versionadded:: 3.8 ``_USE_POSIX_SPAWN`` 1637.. versionadded:: 3.11 ``_USE_VFORK`` 1638