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