Debian Codegraph @

Doc/library/subprocess.rst

raw
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
14 The :mod:`subprocess` module allows you to spawn new processes, connect to their
15 input/output/error pipes, and obtain their return codes. This module intends to
16 replace several older modules and functions::
17
18 os.system
19 os.spawn*
20
21 Information about how the :mod:`subprocess` module can be used to replace these
22 modules 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
30 Using the :mod:`subprocess` Module
31 ----------------------------------
32
33 The recommended approach to invoking subprocesses is to use the :func:`run`
34 function for all use cases it can handle. For more advanced use cases, the
35 underlying :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
269 Frequently Used Arguments
270 ^^^^^^^^^^^^^^^^^^^^^^^^^
271
272 To support a wide variety of use cases, the :class:`Popen` constructor (and
273 the convenience functions) accept a large number of optional arguments. For
274 most typical use cases, many of these arguments can be safely left at their
275 default 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
346 These options, along with all of the other options, are described in more
347 detail in the :class:`Popen` constructor documentation.
348
349
350 Popen Constructor
351 ^^^^^^^^^^^^^^^^^
352
353 The underlying process creation and management in this module is handled by
354 the :class:`Popen` class. It offers a lot of flexibility so that developers
355 are able to handle the less common cases not covered by the convenience
356 functions.
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 ``%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
723 Exceptions
724 ^^^^^^^^^^
725
726 Exceptions raised in the child process, before the new program has started to
727 execute, will be re-raised in the parent.
728
729 The most common exception raised is :exc:`OSError`. This occurs, for example,
730 when trying to execute a non-existent file. Applications should prepare for
731 :exc:`OSError` exceptions. Note that, when ``shell=True``, :exc:`OSError`
732 will be raised by the child only if the selected shell itself was not found.
733 To determine if the shell failed to find the requested application, it is
734 necessary to check the return code or output from the subprocess.
735
736 A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid
737 arguments.
738
739 :func:`check_call` and :func:`check_output` will raise
740 :exc:`CalledProcessError` if the called process returns a non-zero return
741 code.
742
743 All of the functions and methods that accept a *timeout* parameter, such as
744 :func:`run` and :meth:`Popen.communicate` will raise :exc:`TimeoutExpired` if
745 the timeout expires before the process exits.
746
747 Exceptions 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
754 Security Considerations
755 -----------------------
756
757 Unlike some other popen functions, this library will not
758 implicitly choose to call a system shell. This means that all characters,
759 including shell metacharacters, can safely be passed to child processes.
760 If the shell is invoked explicitly, via ``shell=True``, it is the application's
761 responsibility to ensure that all whitespace and metacharacters are
762 quoted appropriately to avoid
763 `shell injection <https://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_
764 vulnerabilities. On :ref:`some platforms <shlex-quote-warning>`, it is possible
765 to use :func:`shlex.quote` for this escaping.
766
767 On Windows, batch files (:file:`*.bat` or :file:`*.cmd`) may be launched by the
768 operating system in a system shell regardless of the arguments passed to this
769 library. This could result in arguments being parsed according to shell rules,
770 but without any escaping added by Python. If you are intentionally launching a
771 batch file with arguments from untrusted sources, consider passing
772 ``shell=True`` to allow Python to escape special characters. See :gh:`114539`
773 for additional discussion.
774
775
776 Popen Objects
777 -------------
778
779 Instances 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. Supplying *input* to a
835 subsequent post-timeout :meth:`communicate` call is in undefined behavior
836 and may become an error in the future.
837
838 The child process is not killed if the timeout expires, so in order to
839 cleanup properly a well-behaved application should kill the child process and
840 finish communication::
841
842 proc = subprocess.Popen(...)
843 try:
844 outs, errs = proc.communicate(timeout=15)
845 except TimeoutExpired:
846 proc.kill()
847 outs, errs = proc.communicate()
848
849 After a call to :meth:`~Popen.communicate` raises :exc:`TimeoutExpired`, do
850 not call :meth:`~Popen.wait`. Use an additional :meth:`~Popen.communicate`
851 call to finish handling pipes and populate the :attr:`~Popen.returncode`
852 attribute.
853
854 .. note::
855
856 The data read is buffered in memory, so do not use this method if the data
857 size is large or unlimited.
858
859 .. versionchanged:: 3.3
860 *timeout* was added.
861
862
863 .. method:: Popen.send_signal(signal)
864
865 Sends the signal *signal* to the child.
866
867 Do nothing if the process completed.
868
869 .. note::
870
871 On Windows, SIGTERM is an alias for :meth:`terminate`. CTRL_C_EVENT and
872 CTRL_BREAK_EVENT can be sent to processes started with a *creationflags*
873 parameter which includes ``CREATE_NEW_PROCESS_GROUP``.
874
875
876 .. method:: Popen.terminate()
877
878 Stop the child. On POSIX OSs the method sends :py:const:`~signal.SIGTERM` to the
879 child. On Windows the Win32 API function :c:func:`!TerminateProcess` is called
880 to stop the child.
881
882
883 .. method:: Popen.kill()
884
885 Kills the child. On POSIX OSs the function sends SIGKILL to the child.
886 On Windows :meth:`kill` is an alias for :meth:`terminate`.
887
888
889 The following attributes are also set by the class for you to access.
890 Reassigning them to new values is unsupported:
891
892 .. attribute:: Popen.args
893
894 The *args* argument as it was passed to :class:`Popen` -- a
895 sequence of program arguments or else a single string.
896
897 .. versionadded:: 3.3
898
899 .. attribute:: Popen.stdin
900
901 If the *stdin* argument was :data:`PIPE`, this attribute is a writeable
902 stream object as returned by :func:`open`. If the *encoding* or *errors*
903 arguments were specified or the *text* or *universal_newlines* argument
904 was ``True``, the stream is a text stream, otherwise it is a byte stream.
905 If the *stdin* argument was not :data:`PIPE`, this attribute is ``None``.
906
907
908 .. attribute:: Popen.stdout
909
910 If the *stdout* argument was :data:`PIPE`, this attribute is a readable
911 stream object as returned by :func:`open`. Reading from the stream provides
912 output from the child process. If the *encoding* or *errors* arguments were
913 specified or the *text* or *universal_newlines* argument was ``True``, the
914 stream is a text stream, otherwise it is a byte stream. If the *stdout*
915 argument was not :data:`PIPE`, this attribute is ``None``.
916
917
918 .. attribute:: Popen.stderr
919
920 If the *stderr* argument was :data:`PIPE`, this attribute is a readable
921 stream object as returned by :func:`open`. Reading from the stream provides
922 error output from the child process. If the *encoding* or *errors* arguments
923 were specified or the *text* or *universal_newlines* argument was ``True``, the
924 stream is a text stream, otherwise it is a byte stream. If the *stderr* argument
925 was not :data:`PIPE`, this attribute is ``None``.
926
927 .. warning::
928
929 Use :meth:`~Popen.communicate` rather than :attr:`.stdin.write <Popen.stdin>`,
930 :attr:`.stdout.read <Popen.stdout>` or :attr:`.stderr.read <Popen.stderr>` to avoid
931 deadlocks due to any of the other OS pipe buffers filling up and blocking the
932 child process.
933
934
935 .. attribute:: Popen.pid
936
937 The process ID of the child process.
938
939 Note that if you set the *shell* argument to ``True``, this is the process ID
940 of the spawned shell.
941
942
943 .. attribute:: Popen.returncode
944
945 The child return code. Initially ``None``, :attr:`returncode` is set by
946 a call to the :meth:`poll`, :meth:`wait`, or :meth:`communicate` methods
947 if they detect that the process has terminated.
948
949 A ``None`` value indicates that the process hadn't yet terminated at the
950 time of the last method call.
951
952 A negative value ``-N`` indicates that the child was terminated by signal
953 ``N`` (POSIX only).
954
955
956 Windows Popen Helpers
957 ---------------------
958
959 The :class:`STARTUPINFO` class and following constants are only available
960 on Windows.
961
962 .. class:: STARTUPINFO(*, dwFlags=0, hStdInput=None, hStdOutput=None, \
963 hStdError=None, wShowWindow=0, lpAttributeList=None)
964
965 Partial support of the Windows
966 `STARTUPINFO <https://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx>`__
967 structure is used for :class:`Popen` creation. The following attributes can
968 be set by passing them as keyword-only arguments.
969
970 .. versionchanged:: 3.7
971 Keyword-only argument support was added.
972
973 .. attribute:: dwFlags
974
975 A bit field that determines whether certain :class:`STARTUPINFO`
976 attributes are used when the process creates a window. ::
977
978 si = subprocess.STARTUPINFO()
979 si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
980
981 .. attribute:: hStdInput
982
983 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
984 is the standard input handle for the process. If
985 :data:`STARTF_USESTDHANDLES` is not specified, the default for standard
986 input is the keyboard buffer.
987
988 .. attribute:: hStdOutput
989
990 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
991 is the standard output handle for the process. Otherwise, this attribute
992 is ignored and the default for standard output is the console window's
993 buffer.
994
995 .. attribute:: hStdError
996
997 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
998 is the standard error handle for the process. Otherwise, this attribute is
999 ignored and the default for standard error is the console window's buffer.
1000
1001 .. attribute:: wShowWindow
1002
1003 If :attr:`dwFlags` specifies :data:`STARTF_USESHOWWINDOW`, this attribute
1004 can be any of the values that can be specified in the ``nCmdShow``
1005 parameter for the
1006 `ShowWindow <https://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx>`__
1007 function, except for ``SW_SHOWDEFAULT``. Otherwise, this attribute is
1008 ignored.
1009
1010 :data:`SW_HIDE` is provided for this attribute. It is used when
1011 :class:`Popen` is called with ``shell=True``.
1012
1013 .. attribute:: lpAttributeList
1014
1015 A dictionary of additional attributes for process creation as given in
1016 ``STARTUPINFOEX``, see
1017 `UpdateProcThreadAttribute <https://msdn.microsoft.com/en-us/library/windows/desktop/ms686880(v=vs.85).aspx>`__.
1018
1019 Supported attributes:
1020
1021 **handle_list**
1022 Sequence of handles that will be inherited. *close_fds* must be true if
1023 non-empty.
1024
1025 The handles must be temporarily made inheritable by
1026 :func:`os.set_handle_inheritable` when passed to the :class:`Popen`
1027 constructor, else :class:`OSError` will be raised with Windows error
1028 ``ERROR_INVALID_PARAMETER`` (87).
1029
1030 .. warning::
1031
1032 In a multithreaded process, use caution to avoid leaking handles
1033 that are marked inheritable when combining this feature with
1034 concurrent calls to other process creation functions that inherit
1035 all handles such as :func:`os.system`. This also applies to
1036 standard handle redirection, which temporarily creates inheritable
1037 handles.
1038
1039 .. versionadded:: 3.7
1040
1041 Windows Constants
1042 ^^^^^^^^^^^^^^^^^
1043
1044 The :mod:`subprocess` module exposes the following constants.
1045
1046 .. data:: STD_INPUT_HANDLE
1047
1048 The standard input device. Initially, this is the console input buffer,
1049 ``CONIN$``.
1050
1051 .. data:: STD_OUTPUT_HANDLE
1052
1053 The standard output device. Initially, this is the active console screen
1054 buffer, ``CONOUT$``.
1055
1056 .. data:: STD_ERROR_HANDLE
1057
1058 The standard error device. Initially, this is the active console screen
1059 buffer, ``CONOUT$``.
1060
1061 .. data:: SW_HIDE
1062
1063 Hides the window. Another window will be activated.
1064
1065 .. data:: STARTF_USESTDHANDLES
1066
1067 Specifies that the :attr:`STARTUPINFO.hStdInput`,
1068 :attr:`STARTUPINFO.hStdOutput`, and :attr:`STARTUPINFO.hStdError` attributes
1069 contain additional information.
1070
1071 .. data:: STARTF_USESHOWWINDOW
1072
1073 Specifies that the :attr:`STARTUPINFO.wShowWindow` attribute contains
1074 additional information.
1075
1076 .. data:: STARTF_FORCEONFEEDBACK
1077
1078 A :attr:`STARTUPINFO.dwFlags` parameter to specify that the
1079 *Working in Background* mouse cursor will be displayed while a
1080 process is launching. This is the default behavior for GUI
1081 processes.
1082
1083 .. versionadded:: 3.13
1084
1085 .. data:: STARTF_FORCEOFFFEEDBACK
1086
1087 A :attr:`STARTUPINFO.dwFlags` parameter to specify that the mouse
1088 cursor will not be changed when launching a process.
1089
1090 .. versionadded:: 3.13
1091
1092 .. data:: CREATE_NEW_CONSOLE
1093
1094 The new process has a new console, instead of inheriting its parent's
1095 console (the default).
1096
1097 .. data:: CREATE_NEW_PROCESS_GROUP
1098
1099 A :class:`Popen` ``creationflags`` parameter to specify that a new process
1100 group will be created. This flag is necessary for using :func:`os.kill`
1101 on the subprocess.
1102
1103 This flag is ignored if :data:`CREATE_NEW_CONSOLE` is specified.
1104
1105 .. data:: ABOVE_NORMAL_PRIORITY_CLASS
1106
1107 A :class:`Popen` ``creationflags`` parameter to specify that a new process
1108 will have an above average priority.
1109
1110 .. versionadded:: 3.7
1111
1112 .. data:: BELOW_NORMAL_PRIORITY_CLASS
1113
1114 A :class:`Popen` ``creationflags`` parameter to specify that a new process
1115 will have a below average priority.
1116
1117 .. versionadded:: 3.7
1118
1119 .. data:: HIGH_PRIORITY_CLASS
1120
1121 A :class:`Popen` ``creationflags`` parameter to specify that a new process
1122 will have a high priority.
1123
1124 .. versionadded:: 3.7
1125
1126 .. data:: IDLE_PRIORITY_CLASS
1127
1128 A :class:`Popen` ``creationflags`` parameter to specify that a new process
1129 will have an idle (lowest) priority.
1130
1131 .. versionadded:: 3.7
1132
1133 .. data:: NORMAL_PRIORITY_CLASS
1134
1135 A :class:`Popen` ``creationflags`` parameter to specify that a new process
1136 will have a normal priority. (default)
1137
1138 .. versionadded:: 3.7
1139
1140 .. data:: REALTIME_PRIORITY_CLASS
1141
1142 A :class:`Popen` ``creationflags`` parameter to specify that a new process
1143 will have realtime priority.
1144 You should almost never use REALTIME_PRIORITY_CLASS, because this interrupts
1145 system threads that manage mouse input, keyboard input, and background disk
1146 flushing. This class can be appropriate for applications that "talk" directly
1147 to hardware or that perform brief tasks that should have limited interruptions.
1148
1149 .. versionadded:: 3.7
1150
1151 .. data:: CREATE_NO_WINDOW
1152
1153 A :class:`Popen` ``creationflags`` parameter to specify that a new process
1154 will not create a window.
1155
1156 .. versionadded:: 3.7
1157
1158 .. data:: DETACHED_PROCESS
1159
1160 A :class:`Popen` ``creationflags`` parameter to specify that a new process
1161 will not inherit its parent's console.
1162 This value cannot be used with CREATE_NEW_CONSOLE.
1163
1164 .. versionadded:: 3.7
1165
1166 .. data:: CREATE_DEFAULT_ERROR_MODE
1167
1168 A :class:`Popen` ``creationflags`` parameter to specify that a new process
1169 does not inherit the error mode of the calling process. Instead, the new
1170 process gets the default error mode.
1171 This feature is particularly useful for multithreaded shell applications
1172 that run with hard errors disabled.
1173
1174 .. versionadded:: 3.7
1175
1176 .. data:: CREATE_BREAKAWAY_FROM_JOB
1177
1178 A :class:`Popen` ``creationflags`` parameter to specify that a new process
1179 is not associated with the job.
1180
1181 .. versionadded:: 3.7
1182
1183 .. _call-function-trio:
1184
1185 Older high-level API
1186 --------------------
1187
1188 Prior to Python 3.5, these three functions comprised the high level API to
1189 subprocess. You can now use :func:`run` in many cases, but lots of existing code
1190 calls these functions.
1191
1192 .. function:: call(args, *, stdin=None, stdout=None, stderr=None, \
1193 shell=False, cwd=None, timeout=None, **other_popen_kwargs)
1194
1195 Run the command described by *args*. Wait for command to complete, then
1196 return the :attr:`~Popen.returncode` attribute.
1197
1198 Code needing to capture stdout or stderr should use :func:`run` instead::
1199
1200 run(...).returncode
1201
1202 To suppress stdout or stderr, supply a value of :data:`DEVNULL`.
1203
1204 The arguments shown above are merely some common ones.
1205 The full function signature is the
1206 same as that of the :class:`Popen` constructor - this function passes all
1207 supplied arguments other than *timeout* directly through to that interface.
1208
1209 .. note::
1210
1211 Do not use ``stdout=PIPE`` or ``stderr=PIPE`` with this
1212 function. The child process will block if it generates enough
1213 output to a pipe to fill up the OS pipe buffer as the pipes are
1214 not being read from.
1215
1216 .. versionchanged:: 3.3
1217 *timeout* was added.
1218
1219 .. versionchanged:: 3.12
1220
1221 Changed Windows shell search order for ``shell=True``. The current
1222 directory and ``%PATH%`` are replaced with ``%COMSPEC%`` and
1223 ``%SystemRoot%\System32\cmd.exe``. As a result, dropping a
1224 malicious program named ``cmd.exe`` into a current directory no
1225 longer works.
1226
1227 .. function:: check_call(args, *, stdin=None, stdout=None, stderr=None, \
1228 shell=False, cwd=None, timeout=None, \
1229 **other_popen_kwargs)
1230
1231 Run command with arguments. Wait for command to complete. If the return
1232 code was zero then return, otherwise raise :exc:`CalledProcessError`. The
1233 :exc:`CalledProcessError` object will have the return code in the
1234 :attr:`~CalledProcessError.returncode` attribute.
1235 If :func:`check_call` was unable to start the process it will propagate the exception
1236 that was raised.
1237
1238 Code needing to capture stdout or stderr should use :func:`run` instead::
1239
1240 run(..., check=True)
1241
1242 To suppress stdout or stderr, supply a value of :data:`DEVNULL`.
1243
1244 The arguments shown above are merely some common ones.
1245 The full function signature is the
1246 same as that of the :class:`Popen` constructor - this function passes all
1247 supplied arguments other than *timeout* directly through to that interface.
1248
1249 .. note::
1250
1251 Do not use ``stdout=PIPE`` or ``stderr=PIPE`` with this
1252 function. The child process will block if it generates enough
1253 output to a pipe to fill up the OS pipe buffer as the pipes are
1254 not being read from.
1255
1256 .. versionchanged:: 3.3
1257 *timeout* was added.
1258
1259 .. versionchanged:: 3.12
1260
1261 Changed Windows shell search order for ``shell=True``. The current
1262 directory and ``%PATH%`` are replaced with ``%COMSPEC%`` and
1263 ``%SystemRoot%\System32\cmd.exe``. As a result, dropping a
1264 malicious program named ``cmd.exe`` into a current directory no
1265 longer works.
1266
1267
1268 .. function:: check_output(args, *, stdin=None, stderr=None, shell=False, \
1269 cwd=None, encoding=None, errors=None, \
1270 universal_newlines=None, timeout=None, text=None, \
1271 **other_popen_kwargs)
1272
1273 Run command with arguments and return its output.
1274
1275 If the return code was non-zero it raises a :exc:`CalledProcessError`. The
1276 :exc:`CalledProcessError` object will have the return code in the
1277 :attr:`~CalledProcessError.returncode` attribute and any output in the
1278 :attr:`~CalledProcessError.output` attribute.
1279
1280 This is equivalent to::
1281
1282 run(..., check=True, stdout=PIPE).stdout
1283
1284 The arguments shown above are merely some common ones.
1285 The full function signature is largely the same as that of :func:`run` -
1286 most arguments are passed directly through to that interface.
1287 One API deviation from :func:`run` behavior exists: passing ``input=None``
1288 will behave the same as ``input=b''`` (or ``input=''``, depending on other
1289 arguments) rather than using the parent's standard input file handle.
1290
1291 By default, this function will return the data as encoded bytes. The actual
1292 encoding of the output data may depend on the command being invoked, so the
1293 decoding to text will often need to be handled at the application level.
1294
1295 This behaviour may be overridden by setting *text*, *encoding*, *errors*,
1296 or *universal_newlines* to ``True`` as described in
1297 :ref:`frequently-used-arguments` and :func:`run`.
1298
1299 To also capture standard error in the result, use
1300 ``stderr=subprocess.STDOUT``::
1301
1302 >>> subprocess.check_output(
1303 ... "ls non_existent_file; exit 0",
1304 ... stderr=subprocess.STDOUT,
1305 ... shell=True)
1306 'ls: non_existent_file: No such file or directory\n'
1307
1308 .. versionadded:: 3.1
1309
1310 .. versionchanged:: 3.3
1311 *timeout* was added.
1312
1313 .. versionchanged:: 3.4
1314 Support for the *input* keyword argument was added.
1315
1316 .. versionchanged:: 3.6
1317 *encoding* and *errors* were added. See :func:`run` for details.
1318
1319 .. versionadded:: 3.7
1320 *text* was added as a more readable alias for *universal_newlines*.
1321
1322 .. versionchanged:: 3.12
1323
1324 Changed Windows shell search order for ``shell=True``. The current
1325 directory and ``%PATH%`` are replaced with ``%COMSPEC%`` and
1326 ``%SystemRoot%\System32\cmd.exe``. As a result, dropping a
1327 malicious program named ``cmd.exe`` into a current directory no
1328 longer works.
1329
1330
1331 .. _subprocess-replacements:
1332
1333 Replacing Older Functions with the :mod:`subprocess` Module
1334 -----------------------------------------------------------
1335
1336 In this section, "a becomes b" means that b can be used as a replacement for a.
1337
1338 .. note::
1339
1340 All "a" functions in this section fail (more or less) silently if the
1341 executed program cannot be found; the "b" replacements raise :exc:`OSError`
1342 instead.
1343
1344 In addition, the replacements using :func:`check_output` will fail with a
1345 :exc:`CalledProcessError` if the requested operation produces a non-zero
1346 return code. The output is still available as the
1347 :attr:`~CalledProcessError.output` attribute of the raised exception.
1348
1349 In the following examples, we assume that the relevant functions have already
1350 been imported from the :mod:`subprocess` module.
1351
1352
1353 Replacing :program:`/bin/sh` shell command substitution
1354 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1355
1356 .. code-block:: bash
1357
1358 output=$(mycmd myarg)
1359
1360 becomes::
1361
1362 output = check_output(["mycmd", "myarg"])
1363
1364 Replacing shell pipeline
1365 ^^^^^^^^^^^^^^^^^^^^^^^^
1366
1367 .. code-block:: bash
1368
1369 output=$(dmesg | grep hda)
1370
1371 becomes::
1372
1373 p1 = Popen(["dmesg"], stdout=PIPE)
1374 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
1375 p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
1376 output = p2.communicate()[0]
1377
1378 The ``p1.stdout.close()`` call after starting the p2 is important in order for
1379 p1 to receive a SIGPIPE if p2 exits before p1.
1380
1381 Alternatively, for trusted input, the shell's own pipeline support may still
1382 be used directly:
1383
1384 .. code-block:: bash
1385
1386 output=$(dmesg | grep hda)
1387
1388 becomes::
1389
1390 output = check_output("dmesg | grep hda", shell=True)
1391
1392
1393 Replacing :func:`os.system`
1394 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
1395
1396 ::
1397
1398 sts = os.system("mycmd" + " myarg")
1399 # becomes
1400 retcode = call("mycmd" + " myarg", shell=True)
1401
1402 Notes:
1403
1404 * Calling the program through the shell is usually not required.
1405 * The :func:`call` return value is encoded differently to that of
1406 :func:`os.system`.
1407
1408 * The :func:`os.system` function ignores SIGINT and SIGQUIT signals while
1409 the command is running, but the caller must do this separately when
1410 using the :mod:`subprocess` module.
1411
1412 A more realistic example would look like this::
1413
1414 try:
1415 retcode = call("mycmd" + " myarg", shell=True)
1416 if retcode < 0:
1417 print("Child was terminated by signal", -retcode, file=sys.stderr)
1418 else:
1419 print("Child returned", retcode, file=sys.stderr)
1420 except OSError as e:
1421 print("Execution failed:", e, file=sys.stderr)
1422
1423
1424 Replacing the :func:`os.spawn <os.spawnl>` family
1425 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1426
1427 P_NOWAIT example::
1428
1429 pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
1430 ==>
1431 pid = Popen(["/bin/mycmd", "myarg"]).pid
1432
1433 P_WAIT example::
1434
1435 retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
1436 ==>
1437 retcode = call(["/bin/mycmd", "myarg"])
1438
1439 Vector example::
1440
1441 os.spawnvp(os.P_NOWAIT, path, args)
1442 ==>
1443 Popen([path] + args[1:])
1444
1445 Environment example::
1446
1447 os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
1448 ==>
1449 Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
1450
1451
1452
1453 Replacing :func:`os.popen`, :func:`os.popen2`, :func:`os.popen3`
1454 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1455
1456 ::
1457
1458 (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
1459 ==>
1460 p = Popen(cmd, shell=True, bufsize=bufsize,
1461 stdin=PIPE, stdout=PIPE, close_fds=True)
1462 (child_stdin, child_stdout) = (p.stdin, p.stdout)
1463
1464 ::
1465
1466 (child_stdin,
1467 child_stdout,
1468 child_stderr) = os.popen3(cmd, mode, bufsize)
1469 ==>
1470 p = Popen(cmd, shell=True, bufsize=bufsize,
1471 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
1472 (child_stdin,
1473 child_stdout,
1474 child_stderr) = (p.stdin, p.stdout, p.stderr)
1475
1476 ::
1477
1478 (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
1479 ==>
1480 p = Popen(cmd, shell=True, bufsize=bufsize,
1481 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
1482 (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
1483
1484 Return code handling translates as follows::
1485
1486 pipe = os.popen(cmd, 'w')
1487 ...
1488 rc = pipe.close()
1489 if rc is not None and rc >> 8:
1490 print("There were some errors")
1491 ==>
1492 process = Popen(cmd, stdin=PIPE)
1493 ...
1494 process.stdin.close()
1495 if process.wait() != 0:
1496 print("There were some errors")
1497
1498
1499 Replacing functions from the :mod:`!popen2` module
1500 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1501
1502 .. note::
1503
1504 If the cmd argument to popen2 functions is a string, the command is executed
1505 through /bin/sh. If it is a list, the command is directly executed.
1506
1507 ::
1508
1509 (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
1510 ==>
1511 p = Popen("somestring", shell=True, bufsize=bufsize,
1512 stdin=PIPE, stdout=PIPE, close_fds=True)
1513 (child_stdout, child_stdin) = (p.stdout, p.stdin)
1514
1515 ::
1516
1517 (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
1518 ==>
1519 p = Popen(["mycmd", "myarg"], bufsize=bufsize,
1520 stdin=PIPE, stdout=PIPE, close_fds=True)
1521 (child_stdout, child_stdin) = (p.stdout, p.stdin)
1522
1523 :class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as
1524 :class:`subprocess.Popen`, except that:
1525
1526 * :class:`Popen` raises an exception if the execution fails.
1527
1528 * The *capturestderr* argument is replaced with the *stderr* argument.
1529
1530 * ``stdin=PIPE`` and ``stdout=PIPE`` must be specified.
1531
1532 * popen2 closes all file descriptors by default, but you have to specify
1533 ``close_fds=True`` with :class:`Popen` to guarantee this behavior on
1534 all platforms or past Python versions.
1535
1536
1537 Legacy Shell Invocation Functions
1538 ---------------------------------
1539
1540 This module also provides the following legacy functions from the 2.x
1541 ``commands`` module. These operations implicitly invoke the system shell and
1542 none of the guarantees described above regarding security and exception
1543 handling consistency are valid for these functions.
1544
1545 .. function:: getstatusoutput(cmd, *, encoding=None, errors=None)
1546
1547 Return ``(exitcode, output)`` of executing *cmd* in a shell.
1548
1549 Execute the string *cmd* in a shell with :func:`check_output` and
1550 return a 2-tuple ``(exitcode, output)``.
1551 *encoding* and *errors* are used to decode output;
1552 see the notes on :ref:`frequently-used-arguments` for more details.
1553
1554 A trailing newline is stripped from the output.
1555 The exit code for the command can be interpreted as the return code
1556 of subprocess. Example::
1557
1558 >>> subprocess.getstatusoutput('ls /bin/ls')
1559 (0, '/bin/ls')
1560 >>> subprocess.getstatusoutput('cat /bin/junk')
1561 (1, 'cat: /bin/junk: No such file or directory')
1562 >>> subprocess.getstatusoutput('/bin/junk')
1563 (127, 'sh: /bin/junk: not found')
1564 >>> subprocess.getstatusoutput('/bin/kill $$')
1565 (-15, '')
1566
1567 .. availability:: Unix, Windows.
1568
1569 .. versionchanged:: 3.3.4
1570 Windows support was added.
1571
1572 The function now returns (exitcode, output) instead of (status, output)
1573 as it did in Python 3.3.3 and earlier. exitcode has the same value as
1574 :attr:`~Popen.returncode`.
1575
1576 .. versionchanged:: 3.11
1577 Added the *encoding* and *errors* parameters.
1578
1579 .. function:: getoutput(cmd, *, encoding=None, errors=None)
1580
1581 Return output (stdout and stderr) of executing *cmd* in a shell.
1582
1583 Like :func:`getstatusoutput`, except the exit code is ignored and the return
1584 value is a string containing the command's output. Example::
1585
1586 >>> subprocess.getoutput('ls /bin/ls')
1587 '/bin/ls'
1588
1589 .. availability:: Unix, Windows.
1590
1591 .. versionchanged:: 3.3.4
1592 Windows support added
1593
1594 .. versionchanged:: 3.11
1595 Added the *encoding* and *errors* parameters.
1596
1597
1598 Notes
1599 -----
1600
1601 .. _subprocess-timeout-behavior:
1602
1603 Timeout Behavior
1604 ^^^^^^^^^^^^^^^^
1605
1606 When using the ``timeout`` parameter in functions like :func:`run`,
1607 :meth:`Popen.wait`, or :meth:`Popen.communicate`,
1608 users should be aware of the following behaviors:
1609
1610 1. **Process Creation Delay**: The initial process creation itself cannot be interrupted
1611 on many platform APIs. This means that even when specifying a timeout, you are not
1612 guaranteed to see a timeout exception until at least after however long process
1613 creation takes.
1614
1615 2. **Extremely Small Timeout Values**: Setting very small timeout values (such as a few
1616 milliseconds) may result in almost immediate :exc:`TimeoutExpired` exceptions because
1617 process creation and system scheduling inherently require time.
1618
1619 .. _converting-argument-sequence:
1620
1621 Converting an argument sequence to a string on Windows
1622 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1623
1624 On Windows, an *args* sequence is converted to a string that can be parsed
1625 using the following rules (which correspond to the rules used by the MS C
1626 runtime):
1627
1628 1. Arguments are delimited by white space, which is either a
1629 space or a tab.
1630
1631 2. A string surrounded by double quotation marks is
1632 interpreted as a single argument, regardless of white space
1633 contained within. A quoted string can be embedded in an
1634 argument.
1635
1636 3. A double quotation mark preceded by a backslash is
1637 interpreted as a literal double quotation mark.
1638
1639 4. Backslashes are interpreted literally, unless they
1640 immediately precede a double quotation mark.
1641
1642 5. If backslashes immediately precede a double quotation mark,
1643 every pair of backslashes is interpreted as a literal
1644 backslash. If the number of backslashes is odd, the last
1645 backslash escapes the next double quotation mark as
1646 described in rule 3.
1647
1648
1649 .. seealso::
1650
1651 :mod:`shlex`
1652 Module which provides function to parse and escape command lines.
1653
1654
1655 .. _disable_vfork:
1656 .. _disable_posix_spawn:
1657
1658 Disabling use of ``vfork()`` or ``posix_spawn()``
1659 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1660
1661 On Linux, :mod:`subprocess` defaults to using the ``vfork()`` system call
1662 internally when it is safe to do so rather than ``fork()``. This greatly
1663 improves performance.
1664
1665 If you ever encounter a presumed highly unusual situation where you need to
1666 prevent ``vfork()`` from being used by Python, you can set the
1667 :const:`subprocess._USE_VFORK` attribute to a false value.
1668
1669 ::
1670
1671 subprocess._USE_VFORK = False # See CPython issue gh-NNNNNN.
1672
1673 Setting this has no impact on use of ``posix_spawn()`` which could use
1674 ``vfork()`` internally within its libc implementation. There is a similar
1675 :const:`subprocess._USE_POSIX_SPAWN` attribute if you need to prevent use of
1676 that.
1677
1678 ::
1679
1680 subprocess._USE_POSIX_SPAWN = False # See CPython issue gh-NNNNNN.
1681
1682 It is safe to set these to false on any Python version. They will have no
1683 effect on older versions when unsupported. Do not assume the attributes are
1684 available to read. Despite their names, a true value does not indicate that the
1685 corresponding function will be used, only that it may be.
1686
1687 Please file issues any time you have to use these private knobs with a way to
1688 reproduce the issue you were seeing. Link to that issue from a comment in your
1689 code.
1690
1691 .. versionadded:: 3.8 ``_USE_POSIX_SPAWN``
1692 .. versionadded:: 3.11 ``_USE_VFORK``