Repository navigation
Expand file tree
/
Copy pathsubprocess.rst
More file actions
1634 lines (1139 loc) · 60.5 KB
/
Copy pathsubprocess.rst
File metadata and controls
1634 lines (1139 loc) · 60.5 KB
Edit and raw actions
OlderNewer
1
:mod:`!subprocess` --- Subprocess management
2
============================================
3
4
.. module:: subprocess
5
:synopsis: Subprocess management.
6
7
**Source code:** :source:`Lib/subprocess.py`
8
9
--------------
10
11
The :mod:`!subprocess` module allows you to spawn new processes, connect to their
12
input/output/error pipes, and obtain their return codes. This module intends to
13
replace several older modules and functions::
14
15
os.system
16
os.spawn*
17
18
Information about how the :mod:`!subprocess` module can be used to replace these
19
modules and functions can be found in the following sections.
20
21
.. seealso::
22
23
:pep:`324` -- PEP proposing the subprocess module
24
25
.. include:: ../includes/wasm-mobile-notavail.rst
26
27
Using the :mod:`!subprocess` Module
28
-----------------------------------
29
30
The recommended approach to invoking subprocesses is to use the :func:`run`
31
function for all use cases it can handle. For more advanced use cases, the
32
underlying :class:`Popen` interface can be used directly.
33
34
35
.. function:: run(args, *, stdin=None, input=None, stdout=None, stderr=None,\
36
capture_output=False, shell=False, cwd=None, timeout=None, \
37
check=False, encoding=None, errors=None, text=None, env=None, \
38
universal_newlines=None, **other_popen_kwargs)
39
40
Run the command described by *args*. Wait for command to complete, then
41
return a :class:`CompletedProcess` instance.
42
43
The arguments shown above are merely the most common ones, described below
44
in :ref:`frequently-used-arguments` (hence the use of keyword-only notation
45
in the abbreviated signature). The full function signature is largely the
46
same as that of the :class:`Popen` constructor - most of the arguments to
47
this function are passed through to that interface. (*timeout*, *input*,
48
*check*, and *capture_output* are not.)
49
50
If *capture_output* is true, stdout and stderr will be captured.
51
When used, the internal :class:`Popen` object is automatically created with
52
*stdout* and *stderr* both set to :data:`~subprocess.PIPE`.
53
The *stdout* and *stderr* arguments may not be supplied at the same time as *capture_output*.
54
If you wish to capture and combine both streams into one,
55
set *stdout* to :data:`~subprocess.PIPE`
56
and *stderr* to :data:`~subprocess.STDOUT`,
57
instead of using *capture_output*.
58
59
A *timeout* may be specified in seconds, it is internally passed on to
60
:meth:`Popen.communicate`. If the timeout expires, the child process will be
61
killed and waited for. The :exc:`TimeoutExpired` exception will be
62
re-raised after the child process has terminated. The initial process
63
creation itself cannot be interrupted on many platform APIs so you are not
64
guaranteed to see a timeout exception until at least after however long
65
process creation takes.
66
67
The *input* argument is passed to :meth:`Popen.communicate` and thus to the
68
subprocess's stdin. If used it must be a byte sequence, or a string if
69
*encoding* or *errors* is specified or *text* is true. When
70
used, the internal :class:`Popen` object is automatically created with
71
*stdin* set to :data:`~subprocess.PIPE`,
72
and the *stdin* argument may not be used as well.
73
74
If *check* is true, and the process exits with a non-zero exit code, a
75
:exc:`CalledProcessError` exception will be raised. Attributes of that
76
exception hold the arguments, the exit code, and stdout and stderr if they
77
were captured.
78
79
If *encoding* or *errors* are specified, or *text* is true,
80
file objects for stdin, stdout and stderr are opened in text mode using the
81
specified *encoding* and *errors* or the :class:`io.TextIOWrapper` default.
82
The *universal_newlines* argument is equivalent to *text* and is provided
83
for backwards compatibility. By default, file objects are opened in binary mode.
84
85
If *env* is not ``None``, it must be a mapping that defines the environment
86
variables for the new process; these are used instead of the default
87
behavior of inheriting the current process' environment. It is passed
88
directly to :class:`Popen`. This mapping can be str to str on any platform
89
or bytes to bytes on POSIX platforms much like :data:`os.environ` or
90
:data:`os.environb`.
91
92
Examples::
93
94
>>> subprocess.run(["ls", "-l"]) # doesn't capture output
95
CompletedProcess(args=['ls', '-l'], returncode=0)
96
97
>>> subprocess.run("exit 1", shell=True, check=True)
98
Traceback (most recent call last):
99
...
100
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
101
102
>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
103
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
104
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
105
106
.. versionadded:: 3.5
107
108
.. versionchanged:: 3.6
109
110
Added *encoding* and *errors* parameters
111
112
.. versionchanged:: 3.7
113
114
Added the *text* parameter, as a more understandable alias of *universal_newlines*.
115
Added the *capture_output* parameter.
116
117
.. versionchanged:: 3.12
118
119
Changed Windows shell search order for ``shell=True``. The current
120
directory and ``%PATH%`` are replaced with ``%COMSPEC%`` and
121
``%SystemRoot%\System32\cmd.exe``. As a result, dropping a
122
malicious program named ``cmd.exe`` into a current directory no
123
longer works.
124
125
.. class:: CompletedProcess
126
127
The return value from :func:`run`, representing a process that has finished.
128
129
.. attribute:: args
130
131
The arguments used to launch the process. This may be a list or a string.
132
133
.. attribute:: returncode
134
135
Exit status of the child process. Typically, an exit status of 0 indicates
136
that it ran successfully.
137
138
A negative value ``-N`` indicates that the child was terminated by signal
139
``N`` (POSIX only).
140
141
.. attribute:: stdout
142
143
Captured stdout from the child process. A bytes sequence, or a string if
144
:func:`run` was called with an encoding, errors, or text=True.
145
``None`` if stdout was not captured.
146
147
If you ran the process with ``stderr=subprocess.STDOUT``, stdout and
148
stderr will be combined in this attribute, and :attr:`stderr` will be
149
``None``.
150
151
.. attribute:: stderr
152
153
Captured stderr from the child process. A bytes sequence, or a string if
154
:func:`run` was called with an encoding, errors, or text=True.
155
``None`` if stderr was not captured.
156
157
.. method:: check_returncode()
158
159
If :attr:`returncode` is non-zero, raise a :exc:`CalledProcessError`.
160
161
.. versionadded:: 3.5
162
163
.. data:: DEVNULL
164
165
Special value that can be used as the *stdin*, *stdout* or *stderr* argument
166
to :class:`Popen` and indicates that the special file :data:`os.devnull`
167
will be used.
168
169
.. versionadded:: 3.3
170
171
172
.. data:: PIPE
173
174
Special value that can be used as the *stdin*, *stdout* or *stderr* argument
175
to :class:`Popen` and indicates that a pipe to the standard stream should be
176
opened. Most useful with :meth:`Popen.communicate`.
177
178
179
.. data:: STDOUT
180
181
Special value that can be used as the *stderr* argument to :class:`Popen` and
182
indicates that standard error should go into the same handle as standard
183
output.
184
185
186
.. exception:: SubprocessError
187
188
Base class for all other exceptions from this module.
189
190
.. versionadded:: 3.3
191
192
193
.. exception:: TimeoutExpired
194
195
Subclass of :exc:`SubprocessError`, raised when a timeout expires
196
while waiting for a child process.
197
198
.. attribute:: cmd
199
200
Command that was used to spawn the child process.
201
202
.. attribute:: timeout
203
204
Timeout in seconds.
205
206
.. attribute:: output
207
208
Output of the child process if it was captured by :func:`run` or
209
:func:`check_output`. Otherwise, ``None``. This is always
210
:class:`bytes` when any output was captured regardless of the
211
``text=True`` setting. It may remain ``None`` instead of ``b''``
212
when no output was observed.
213
214
.. attribute:: stdout
215
216
Alias for output, for symmetry with :attr:`stderr`.
217
218
.. attribute:: stderr
219
220
Stderr output of the child process if it was captured by :func:`run`.
221
Otherwise, ``None``. This is always :class:`bytes` when stderr output
222
was captured regardless of the ``text=True`` setting. It may remain
223
``None`` instead of ``b''`` when no stderr output was observed.
224
225
.. versionadded:: 3.3
226
227
.. versionchanged:: 3.5
228
*stdout* and *stderr* attributes added
229
230
.. exception:: CalledProcessError
231
232
Subclass of :exc:`SubprocessError`, raised when a process run by
233
:func:`check_call`, :func:`check_output`, or :func:`run` (with ``check=True``)
234
returns a non-zero exit status.
235
236
237
.. attribute:: returncode
238
239
Exit status of the child process, an integer. If the process
240
exited due to a signal, this will be the negative signal number.
241
242
.. attribute:: cmd
243
244
Command that was used to spawn the child process.
245
246
.. attribute:: output
247
248
Output of the child process if it was captured by :func:`run` or
249
:func:`check_output`. Otherwise, ``None``.
250
251
.. attribute:: stdout
252
253
Alias for output, for symmetry with :attr:`stderr`.
254
255
.. attribute:: stderr
256
257
Stderr output of the child process if it was captured by :func:`run`.
258
Otherwise, ``None``.
259
260
.. versionchanged:: 3.5
261
*stdout* and *stderr* attributes added
262
263
264
.. _frequently-used-arguments:
265
266
Frequently Used Arguments
267
^^^^^^^^^^^^^^^^^^^^^^^^^
268
269
To support a wide variety of use cases, the :class:`Popen` constructor (and
270
the convenience functions) accept a large number of optional arguments. For
271
most typical use cases, many of these arguments can be safely left at their
272
default values. The arguments that are most commonly needed are:
273
274
*args* is required for all calls and should be a string, or a sequence of
275
program arguments. Providing a sequence of arguments is generally
276
preferred, as it allows the module to take care of any required escaping
277
and quoting of arguments (e.g. to permit spaces in file names). If passing
278
a single string, either *shell* must be :const:`True` (see below) or else
279
the string must simply name the program to be executed without specifying
280
any arguments.
281
282
*stdin*, *stdout* and *stderr* specify the executed program's standard input,
283
standard output and standard error file handles, respectively. Valid values
284
are ``None``, :data:`PIPE`, :data:`DEVNULL`, an existing file descriptor (a
285
positive integer), and an existing :term:`file object` with a valid file
286
descriptor. With the default settings of ``None``, no redirection will
287
occur. :data:`PIPE` indicates that a new pipe to the child should be
288
created. :data:`DEVNULL` indicates that the special file :data:`os.devnull`
289
will be used. Additionally, *stderr* can be :data:`STDOUT`, which indicates
290
that the stderr data from the child process should be captured into the same
291
file handle as for *stdout*.
292
293
.. index::
294
single: universal newlines; subprocess module
295
296
If *encoding* or *errors* are specified, or *text* (also known as
297
*universal_newlines*) is true,
298
the file objects *stdin*, *stdout* and *stderr* will be opened in text
299
mode using the *encoding* and *errors* specified in the call or the
300
defaults for :class:`io.TextIOWrapper`.
301
302
For *stdin*, line ending characters ``'\n'`` in the input will be converted
303
to the default line separator :data:`os.linesep`. For *stdout* and *stderr*,
304
all line endings in the output will be converted to ``'\n'``. For more
305
information see the documentation of the :class:`io.TextIOWrapper` class
306
when the *newline* argument to its constructor is ``None``.
307
308
If text mode is not used, *stdin*, *stdout* and *stderr* will be opened as
309
binary streams. No encoding or line ending conversion is performed.
310
311
.. versionchanged:: 3.6
312
Added the *encoding* and *errors* parameters.
313
314
.. versionchanged:: 3.7
315
Added the *text* parameter as an alias for *universal_newlines*.
316
317
.. note::
318
319
The newlines attribute of the file objects :attr:`Popen.stdin`,
320
:attr:`Popen.stdout` and :attr:`Popen.stderr` are not updated by
321
the :meth:`Popen.communicate` method.
322
323
If *shell* is ``True``, the specified command will be executed through
324
the shell. This can be useful if you are using Python primarily for the
325
enhanced control flow it offers over most system shells and still want
326
convenient access to other shell features such as shell pipes, filename
327
wildcards, environment variable expansion, and expansion of ``~`` to a
328
user's home directory. However, note that Python itself offers
329
implementations of many shell-like features (in particular, :mod:`glob`,
330
:mod:`fnmatch`, :func:`os.walk`, :func:`os.path.expandvars`,
331
:func:`os.path.expanduser`, and :mod:`shutil`).
332
333
.. versionchanged:: 3.3
334
When *universal_newlines* is ``True``, the class uses the encoding
335
:func:`locale.getpreferredencoding(False) <locale.getpreferredencoding>`
336
instead of ``locale.getpreferredencoding()``. See the
337
:class:`io.TextIOWrapper` class for more information on this change.
338
339
.. note::
340
341
Read the `Security Considerations`_ section before using ``shell=True``.
342
343
These options, along with all of the other options, are described in more
344
detail in the :class:`Popen` constructor documentation.
345
346
347
Popen Constructor
348
^^^^^^^^^^^^^^^^^
349
350
The underlying process creation and management in this module is handled by
351
the :class:`Popen` class. It offers a lot of flexibility so that developers
352
are able to handle the less common cases not covered by the convenience
353
functions.
354
355
356
.. class:: Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, \
357
stderr=None, preexec_fn=None, close_fds=True, shell=False, \
358
cwd=None, env=None, universal_newlines=None, \
359
startupinfo=None, creationflags=0, restore_signals=True, \
360
start_new_session=False, pass_fds=(), *, group=None, \
361
extra_groups=None, user=None, umask=-1, \
362
encoding=None, errors=None, text=None, pipesize=-1, \
363
process_group=None)
364
365
Execute a child program in a new process. On POSIX, the class uses
366
:meth:`os.execvpe`-like behavior to execute the child program. On Windows,
367
the class uses the Windows ``CreateProcess()`` function. The arguments to
368
:class:`Popen` are as follows.
369
370
*args* should be a sequence of program arguments or else a single string
371
or :term:`path-like object`.
372
By default, the program to execute is the first item in *args* if *args* is
373
a sequence. If *args* is a string, the interpretation is
374
platform-dependent and described below. See the *shell* and *executable*
375
arguments for additional differences from the default behavior. Unless
376
otherwise stated, it is recommended to pass *args* as a sequence.
377
378
.. warning::
379
380
For maximum reliability, use a fully qualified path for the executable.
381
To search for an unqualified name on :envvar:`PATH`, use
382
:meth:`shutil.which`. On all platforms, passing :data:`sys.executable`
383
is the recommended way to launch the current Python interpreter again,
384
and use the ``-m`` command-line format to launch an installed module.
385
386
Resolving the path of *executable* (or the first item of *args*) is
387
platform dependent. For POSIX, see :meth:`os.execvpe`, and note that
388
when resolving or searching for the executable path, *cwd* overrides the
389
current working directory and *env* can override the ``PATH``
390
environment variable. For Windows, see the documentation of the
391
``lpApplicationName`` and ``lpCommandLine`` parameters of WinAPI
392
``CreateProcess``, and note that when resolving or searching for the
393
executable path with ``shell=False``, *cwd* does not override the
394
current working directory and *env* cannot override the ``PATH``
395
environment variable. Using a full path avoids all of these variations.
396
397
An example of passing some arguments to an external program
398
as a sequence is::
399
400
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
401
402
On POSIX, if *args* is a string, the string is interpreted as the name or
403
path of the program to execute. However, this can only be done if not
404
passing arguments to the program.
405
406
.. note::
407
408
It may not be obvious how to break a shell command into a sequence of arguments,
409
especially in complex cases. :meth:`shlex.split` can illustrate how to
410
determine the correct tokenization for *args*::
411
412
>>> import shlex, subprocess
413
>>> command_line = input()
414
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
415
>>> args = shlex.split(command_line)
416
>>> print(args)
417
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
418
>>> p = subprocess.Popen(args) # Success!
419
420
Note in particular that options (such as *-input*) and arguments (such
421
as *eggs.txt*) that are separated by whitespace in the shell go in separate
422
list elements, while arguments that need quoting or backslash escaping when
423
used in the shell (such as filenames containing spaces or the *echo* command
424
shown above) are single list elements.
425
426
On Windows, if *args* is a sequence, it will be converted to a string in a
427
manner described in :ref:`converting-argument-sequence`. This is because
428
the underlying ``CreateProcess()`` operates on strings.
429
430
.. versionchanged:: 3.6
431
*args* parameter accepts a :term:`path-like object` if *shell* is
432
``False`` and a sequence containing path-like objects on POSIX.
433
434
.. versionchanged:: 3.8
435
*args* parameter accepts a :term:`path-like object` if *shell* is
436
``False`` and a sequence containing bytes and path-like objects
437
on Windows.
438
439
The *shell* argument (which defaults to ``False``) specifies whether to use
440
the shell as the program to execute. If *shell* is ``True``, it is
441
recommended to pass *args* as a string rather than as a sequence.
442
443
On POSIX with ``shell=True``, the shell defaults to :file:`/bin/sh`. If
444
*args* is a string, the string specifies the command
445
to execute through the shell. This means that the string must be
446
formatted exactly as it would be when typed at the shell prompt. This
447
includes, for example, quoting or backslash escaping filenames with spaces in
448
them. If *args* is a sequence, the first item specifies the command string, and
449
any additional items will be treated as additional arguments to the shell
450
itself. That is to say, :class:`Popen` does the equivalent of::
451
452
Popen(['/bin/sh', '-c', args[0], args[1], ...])
453
454
On Windows with ``shell=True``, the :envvar:`COMSPEC` environment variable
455
specifies the default shell. The only time you need to specify
456
``shell=True`` on Windows is when the command you wish to execute is built
457
into the shell (e.g. :command:`dir` or :command:`copy`). You do not need
458
``shell=True`` to run a batch file or console-based executable.
459
460
.. note::
461
462
Read the `Security Considerations`_ section before using ``shell=True``.
463
464
*bufsize* will be supplied as the corresponding argument to the
465
:func:`open` function when creating the stdin/stdout/stderr pipe
466
file objects:
467
468
- ``0`` means unbuffered (read and write are one
469
system call and can return short)
470
- ``1`` means line buffered
471
(only usable if ``text=True`` or ``universal_newlines=True``)
472
- any other positive value means use a buffer of approximately that
473
size
474
- negative bufsize (the default) means the system default of
475
io.DEFAULT_BUFFER_SIZE will be used.
476
477
.. versionchanged:: 3.3.1
478
*bufsize* now defaults to -1 to enable buffering by default to match the
479
behavior that most code expects. In versions prior to Python 3.2.4 and
480
3.3.1 it incorrectly defaulted to ``0`` which was unbuffered
481
and allowed short reads. This was unintentional and did not match the
482
behavior of Python 2 as most code expected.
483
484
The *executable* argument specifies a replacement program to execute. It
485
is very seldom needed. When ``shell=False``, *executable* replaces the
486
program to execute specified by *args*. However, the original *args* is
487
still passed to the program. Most programs treat the program specified
488
by *args* as the command name, which can then be different from the program
489
actually executed. On POSIX, the *args* name
490
becomes the display name for the executable in utilities such as
491
:program:`ps`. If ``shell=True``, on POSIX the *executable* argument
492
specifies a replacement shell for the default :file:`/bin/sh`.
493
494
.. versionchanged:: 3.6
495
*executable* parameter accepts a :term:`path-like object` on POSIX.
496
497
.. versionchanged:: 3.8
498
*executable* parameter accepts a bytes and :term:`path-like object`
499
on Windows.
500
501
.. versionchanged:: 3.12
502
503
Changed Windows shell search order for ``shell=True``. The current
504
directory and ``%PATH%`` are replaced with ``%COMSPEC%`` and
505
``%SystemRoot%\System32\cmd.exe``. As a result, dropping a
506
malicious program named ``cmd.exe`` into a current directory no
507
longer works.
508
509
*stdin*, *stdout* and *stderr* specify the executed program's standard input,
510
standard output and standard error file handles, respectively. Valid values
511
are ``None``, :data:`PIPE`, :data:`DEVNULL`, an existing file descriptor (a
512
positive integer), and an existing :term:`file object` with a valid file
513
descriptor. With the default settings of ``None``, no redirection will
514
occur. :data:`PIPE` indicates that a new pipe to the child should be
515
created. :data:`DEVNULL` indicates that the special file :data:`os.devnull`
516
will be used. Additionally, *stderr* can be :data:`STDOUT`, which indicates
517
that the stderr data from the applications should be captured into the same
518
file handle as for *stdout*.
519
520
If *preexec_fn* is set to a callable object, this object will be called in the
521
child process just before the child is executed.
522
(POSIX only)
523
524
.. warning::
525
526
The *preexec_fn* parameter is NOT SAFE to use in the presence of threads
527
in your application. The child process could deadlock before exec is
528
called.
529
530
.. note::
531
532
If you need to modify the environment for the child use the *env*
533
parameter rather than doing it in a *preexec_fn*.
534
The *start_new_session* and *process_group* parameters should take the place of
535
code using *preexec_fn* to call :func:`os.setsid` or :func:`os.setpgid` in the child.
536
537
.. versionchanged:: 3.8
538
539
The *preexec_fn* parameter is no longer supported in subinterpreters.
540
The use of the parameter in a subinterpreter raises
541
:exc:`RuntimeError`. The new restriction may affect applications that
542
are deployed in mod_wsgi, uWSGI, and other embedded environments.
543
544
If *close_fds* is true, all file descriptors except ``0``, ``1`` and
545
``2`` will be closed before the child process is executed. Otherwise
546
when *close_fds* is false, file descriptors obey their inheritable flag
547
as described in :ref:`fd_inheritance`.
548
549
On Windows, if *close_fds* is true then no handles will be inherited by the
550
child process unless explicitly passed in the ``handle_list`` element of
551
:attr:`STARTUPINFO.lpAttributeList`, or by standard handle redirection.
552
553
.. versionchanged:: 3.2
554
The default for *close_fds* was changed from :const:`False` to
555
what is described above.
556
557
.. versionchanged:: 3.7
558
On Windows the default for *close_fds* was changed from :const:`False` to
559
:const:`True` when redirecting the standard handles. It's now possible to
560
set *close_fds* to :const:`True` when redirecting the standard handles.
561
562
*pass_fds* is an optional sequence of file descriptors to keep open
563
between the parent and child. Providing any *pass_fds* forces
564
*close_fds* to be :const:`True`. (POSIX only)
565
566
.. versionchanged:: 3.2
567
The *pass_fds* parameter was added.
568
569
If *cwd* is not ``None``, the function changes the working directory to
570
*cwd* before executing the child. *cwd* can be a string, bytes or
571
:term:`path-like <path-like object>` object. On POSIX, the function
572
looks for *executable* (or for the first item in *args*) relative to *cwd*
573
if the executable path is a relative path.
574
575
.. versionchanged:: 3.6
576
*cwd* parameter accepts a :term:`path-like object` on POSIX.
577
578
.. versionchanged:: 3.7
579
*cwd* parameter accepts a :term:`path-like object` on Windows.
580
581
.. versionchanged:: 3.8
582
*cwd* parameter accepts a bytes object on Windows.
583
584
If *restore_signals* is true (the default) all signals that Python has set to
585
SIG_IGN are restored to SIG_DFL in the child process before the exec.
586
Currently this includes the SIGPIPE, SIGXFZ and SIGXFSZ signals.
587
(POSIX only)
588
589
.. versionchanged:: 3.2
590
*restore_signals* was added.
591
592
If *start_new_session* is true the ``setsid()`` system call will be made in the
593
child process prior to the execution of the subprocess.
594
595
.. availability:: POSIX
596
.. versionchanged:: 3.2
597
*start_new_session* was added.
598
599
If *process_group* is a non-negative integer, the ``setpgid(0, value)`` system call will
600
be made in the child process prior to the execution of the subprocess.
601
602
.. availability:: POSIX
603
.. versionchanged:: 3.11
604
*process_group* was added.
605
606
If *group* is not ``None``, the setregid() system call will be made in the
607
child process prior to the execution of the subprocess. If the provided
608
value is a string, it will be looked up via :func:`grp.getgrnam` and
609
the value in ``gr_gid`` will be used. If the value is an integer, it
610
will be passed verbatim. (POSIX only)
611
612
.. availability:: POSIX
613
.. versionadded:: 3.9
614
615
If *extra_groups* is not ``None``, the setgroups() system call will be
616
made in the child process prior to the execution of the subprocess.
617
Strings provided in *extra_groups* will be looked up via
618
:func:`grp.getgrnam` and the values in ``gr_gid`` will be used.
619
Integer values will be passed verbatim. (POSIX only)
620
621
.. availability:: POSIX
622
.. versionadded:: 3.9
623
624
If *user* is not ``None``, the setreuid() system call will be made in the
625
child process prior to the execution of the subprocess. If the provided
626
value is a string, it will be looked up via :func:`pwd.getpwnam` and
627
the value in ``pw_uid`` will be used. If the value is an integer, it will
628
be passed verbatim. (POSIX only)
629
630
.. note::
631
632
Specifying *user* will not drop existing supplementary group memberships!
633
The caller must also pass ``extra_groups=()`` to reduce the group membership
634
of the child process for security purposes.
635
636
.. availability:: POSIX
637
.. versionadded:: 3.9
638
639
If *umask* is not negative, the umask() system call will be made in the
640
child process prior to the execution of the subprocess.
641
642
.. availability:: POSIX
643
.. versionadded:: 3.9
644
645
If *env* is not ``None``, it must be a mapping that defines the environment
646
variables for the new process; these are used instead of the default
647
behavior of inheriting the current process' environment. This mapping can be
648
str to str on any platform or bytes to bytes on POSIX platforms much like
649
:data:`os.environ` or :data:`os.environb`.
650
651
.. note::
652
653
If specified, *env* must provide any variables required for the program to
654
execute. On Windows, in order to run a `side-by-side assembly`_ the
655
specified *env* **must** include a valid ``%SystemRoot%``.
656
657
.. _side-by-side assembly: https://en.wikipedia.org/wiki/Side-by-Side_Assembly
658
659
If *encoding* or *errors* are specified, or *text* is true, the file objects
660
*stdin*, *stdout* and *stderr* are opened in text mode with the specified
661
*encoding* and *errors*, as described above in :ref:`frequently-used-arguments`.
662
The *universal_newlines* argument is equivalent to *text* and is provided
663
for backwards compatibility. By default, file objects are opened in binary mode.
664
665
.. versionadded:: 3.6
666
*encoding* and *errors* were added.
667
668
.. versionadded:: 3.7
669
*text* was added as a more readable alias for *universal_newlines*.
670
671
If given, *startupinfo* will be a :class:`STARTUPINFO` object, which is
672
passed to the underlying ``CreateProcess`` function.
673
674
If given, *creationflags*, can be one or more of the following flags:
675
676
* :data:`CREATE_NEW_CONSOLE`
677
* :data:`CREATE_NEW_PROCESS_GROUP`
678
* :data:`ABOVE_NORMAL_PRIORITY_CLASS`
679
* :data:`BELOW_NORMAL_PRIORITY_CLASS`
680
* :data:`HIGH_PRIORITY_CLASS`
681
* :data:`IDLE_PRIORITY_CLASS`
682
* :data:`NORMAL_PRIORITY_CLASS`
683
* :data:`REALTIME_PRIORITY_CLASS`
684
* :data:`CREATE_NO_WINDOW`
685
* :data:`DETACHED_PROCESS`
686
* :data:`CREATE_DEFAULT_ERROR_MODE`
687
* :data:`CREATE_BREAKAWAY_FROM_JOB`
688
689
*pipesize* can be used to change the size of the pipe when
690
:data:`PIPE` is used for *stdin*, *stdout* or *stderr*. The size of the pipe
691
is only changed on platforms that support this (only Linux at this time of
692
writing). Other platforms will ignore this parameter.
693
694
.. versionchanged:: 3.10
695
Added the *pipesize* parameter.
696
697
Popen objects are supported as context managers via the :keyword:`with` statement:
698
on exit, standard file descriptors are closed, and the process is waited for.
699
::
700
701
with Popen(["ifconfig"], stdout=PIPE) as proc:
702
log.write(proc.stdout.read())
703
704
.. audit-event:: subprocess.Popen executable,args,cwd,env subprocess.Popen
705
706
Popen and the other functions in this module that use it raise an
707
:ref:`auditing event <auditing>` ``subprocess.Popen`` with arguments
708
``executable``, ``args``, ``cwd``, and ``env``. The value for ``args``
709
may be a single string or a list of strings, depending on platform.
710
711
.. versionchanged:: 3.2
712
Added context manager support.
713
714
.. versionchanged:: 3.6
715
Popen destructor now emits a :exc:`ResourceWarning` warning if the child
716
process is still running.
717
718
.. versionchanged:: 3.8
719
Popen can use :func:`os.posix_spawn` in some cases for better
720
performance. On Windows Subsystem for Linux and QEMU User Emulation,
721
Popen constructor using :func:`os.posix_spawn` no longer raise an
722
exception on errors like missing program, but the child process fails
723
with a non-zero :attr:`~Popen.returncode`.
724
725
726
Exceptions
727
^^^^^^^^^^
728
729
Exceptions raised in the child process, before the new program has started to
730
execute, will be re-raised in the parent.
731
732
The most common exception raised is :exc:`OSError`. This occurs, for example,
733
when trying to execute a non-existent file. Applications should prepare for
734
:exc:`OSError` exceptions. Note that, when ``shell=True``, :exc:`OSError`
735
will be raised by the child only if the selected shell itself was not found.
736
To determine if the shell failed to find the requested application, it is
737
necessary to check the return code or output from the subprocess.
738
739
A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid
740
arguments.
741
742
:func:`check_call` and :func:`check_output` will raise
743
:exc:`CalledProcessError` if the called process returns a non-zero return
744
code.
745
746
All of the functions and methods that accept a *timeout* parameter, such as
747
:func:`run` and :meth:`Popen.communicate` will raise :exc:`TimeoutExpired` if
748
the timeout expires before the process exits.
749
750
Exceptions defined in this module all inherit from :exc:`SubprocessError`.
751
752
.. versionadded:: 3.3
753
The :exc:`SubprocessError` base class was added.
754
755
.. _subprocess-security:
756
757
Security Considerations
758
-----------------------
759
760
Unlike some other popen functions, this library will not
761
implicitly choose to call a system shell. This means that all characters,
762
including shell metacharacters, can safely be passed to child processes.
763
If the shell is invoked explicitly, via ``shell=True``, it is the application's
764
responsibility to ensure that all whitespace and metacharacters are
765
quoted appropriately to avoid
766
`shell injection <https://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_
767
vulnerabilities. On :ref:`some platforms <shlex-quote-warning>`, it is possible
768
to use :func:`shlex.quote` for this escaping.
769
770
On Windows, batch files (:file:`*.bat` or :file:`*.cmd`) may be launched by the
771
operating system in a system shell regardless of the arguments passed to this
772
library. This could result in arguments being parsed according to shell rules,
773
but without any escaping added by Python. If you are intentionally launching a
774
batch file with arguments from untrusted sources, consider passing
775
``shell=True`` to allow Python to escape special characters. See :gh:`114539`
776
for additional discussion.
777
778
779
Popen Objects
780
-------------
781
782
Instances of the :class:`Popen` class have the following methods:
783
784
785
.. method:: Popen.poll()
786
787
Check if child process has terminated. Set and return
788
:attr:`~Popen.returncode` attribute. Otherwise, returns ``None``.
789
790
791
.. method:: Popen.wait(timeout=None)
792
793
Wait for child process to terminate. Set and return
794
:attr:`~Popen.returncode` attribute.
795
796
If the process does not terminate after *timeout* seconds, raise a
797
:exc:`TimeoutExpired` exception. It is safe to catch this exception and
798
retry the wait.
799
800
.. note::
801
802
This will deadlock when using ``stdout=PIPE`` or ``stderr=PIPE``
803
and the child process generates enough output to a pipe such that
804
it blocks waiting for the OS pipe buffer to accept more data.
805
Use :meth:`Popen.communicate` when using pipes to avoid that.
806
807
.. note::
808
809
When ``timeout`` is not ``None`` and the platform supports it, an
810
efficient event-driven mechanism is used to wait for process termination:
811
812
- Linux >= 5.3 uses :func:`os.pidfd_open` + :func:`select.poll`
813
- macOS and other BSD variants use :func:`select.kqueue` +
814
``KQ_FILTER_PROC`` + ``KQ_NOTE_EXIT``
815
- Windows uses ``WaitForSingleObject``
816
817
If none of these mechanisms are available, the function falls back to a
818
busy loop (non-blocking call and short sleeps).
819
820
.. note::
821
822
Use the :mod:`asyncio` module for an asynchronous wait: see
823
:class:`asyncio.create_subprocess_exec`.
824
825
.. versionchanged:: 3.3
826
*timeout* was added.
827
828
.. versionchanged:: 3.15
829
if *timeout* is not ``None``, use efficient event-driven implementation
830
on Linux >= 5.3 and macOS / BSD.
831
832
.. method:: Popen.communicate(input=None, timeout=None)
833
834
Interact with process: Send data to stdin. Read data from stdout and stderr,
835
until end-of-file is reached. Wait for process to terminate and set the
836
:attr:`~Popen.returncode` attribute. The optional *input* argument should be
837
data to be sent to the child process, or ``None``, if no data should be sent
838
to the child. If streams were opened in text mode, *input* must be a string.
839
Otherwise, it must be bytes.
840
841
:meth:`communicate` returns a tuple ``(stdout_data, stderr_data)``.
842
The data will be strings if streams were opened in text mode; otherwise,
843
bytes.
844
845
Note that if you want to send data to the process's stdin, you need to create
846
the Popen object with ``stdin=PIPE``. Similarly, to get anything other than
847
``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or
848
``stderr=PIPE`` too.
849
850
If the process does not terminate after *timeout* seconds, a
851
:exc:`TimeoutExpired` exception will be raised. Catching this exception and
852
retrying communication will not lose any output. Supplying *input* to a
853
subsequent post-timeout :meth:`communicate` call is in undefined behavior
854
and may become an error in the future.
855
856
The child process is not killed if the timeout expires, so in order to
857
cleanup properly a well-behaved application should kill the child process and
858
finish communication::
859
860
proc = subprocess.Popen(...)
861
try:
862
outs, errs = proc.communicate(timeout=15)
863
except TimeoutExpired:
864
proc.kill()
865
outs, errs = proc.communicate()
866
867
After a call to :meth:`~Popen.communicate` raises :exc:`TimeoutExpired`, do
868
not call :meth:`~Popen.wait`. Use an additional :meth:`~Popen.communicate`
869
call to finish handling pipes and populate the :attr:`~Popen.returncode`
870
attribute.
871
872
.. note::
873
874
The data read is buffered in memory, so do not use this method if the data
875
size is large or unlimited.
876
877
.. versionchanged:: 3.3
878
*timeout* was added.
879
880
881
.. method:: Popen.send_signal(signal)
882
883
Sends the signal *signal* to the child.
884
885
Do nothing if the process completed.
886
887
.. note::
888
889
On Windows, SIGTERM is an alias for :meth:`terminate`. CTRL_C_EVENT and
890
CTRL_BREAK_EVENT can be sent to processes started with a *creationflags*
891
parameter which includes ``CREATE_NEW_PROCESS_GROUP``.
892
893
894
.. method:: Popen.terminate()
895
896
Stop the child. On POSIX OSs the method sends :py:const:`~signal.SIGTERM` to the
897
child. On Windows the Win32 API function :c:func:`!TerminateProcess` is called
898
to stop the child.
899
900
901
.. method:: Popen.kill()
902
903
Kills the child. On POSIX OSs the function sends SIGKILL to the child.
904
On Windows :meth:`kill` is an alias for :meth:`terminate`.
905
906
907
The following attributes are also set by the class for you to access.
908
Reassigning them to new values is unsupported:
909
910
.. attribute:: Popen.args
911
912
The *args* argument as it was passed to :class:`Popen` -- a
913
sequence of program arguments or else a single string.
914
915
.. versionadded:: 3.3
916
917
.. attribute:: Popen.stdin
918
919
If the *stdin* argument was :data:`PIPE`, this attribute is a writeable
920
stream object as returned by :func:`open`. If the *encoding* or *errors*
921
arguments were specified or the *text* or *universal_newlines* argument
922
was ``True``, the stream is a text stream, otherwise it is a byte stream.
923
If the *stdin* argument was not :data:`PIPE`, this attribute is ``None``.
924
925
926
.. attribute:: Popen.stdout
927
928
If the *stdout* argument was :data:`PIPE`, this attribute is a readable
929
stream object as returned by :func:`open`. Reading from the stream provides
930
output from the child process. If the *encoding* or *errors* arguments were
931
specified or the *text* or *universal_newlines* argument was ``True``, the
932
stream is a text stream, otherwise it is a byte stream. If the *stdout*
933
argument was not :data:`PIPE`, this attribute is ``None``.
934
935
936
.. attribute:: Popen.stderr
937
938
If the *stderr* argument was :data:`PIPE`, this attribute is a readable
939
stream object as returned by :func:`open`. Reading from the stream provides
940
error output from the child process. If the *encoding* or *errors* arguments
941
were specified or the *text* or *universal_newlines* argument was ``True``, the
942
stream is a text stream, otherwise it is a byte stream. If the *stderr* argument
943
was not :data:`PIPE`, this attribute is ``None``.
944
945
.. warning::
946
947
Use :meth:`~Popen.communicate` rather than :attr:`.stdin.write <Popen.stdin>`,
948
:attr:`.stdout.read <Popen.stdout>` or :attr:`.stderr.read <Popen.stderr>` to avoid
949
deadlocks due to any of the other OS pipe buffers filling up and blocking the
950
child process.
951
952
953
.. attribute:: Popen.pid
954
955
The process ID of the child process.
956
957
Note that if you set the *shell* argument to ``True``, this is the process ID
958
of the spawned shell.
959
960
961
.. attribute:: Popen.returncode
962
963
The child return code. Initially ``None``, :attr:`returncode` is set by
964
a call to the :meth:`poll`, :meth:`wait`, or :meth:`communicate` methods
965
if they detect that the process has terminated.
966
967
A ``None`` value indicates that the process hadn't yet terminated at the
968
time of the last method call.
969
970
A negative value ``-N`` indicates that the child was terminated by signal
971
``N`` (POSIX only).
972
973
When ``shell=True``, the return code reflects the exit status of the shell
974
itself (e.g. ``/bin/sh``), which may map signals to codes such as
975
``128+N``. See the documentation of the shell (for example, the Bash
976
manual's Exit Status) for details.
977
978
979
Windows Popen Helpers
980
---------------------
981
982
The :class:`STARTUPINFO` class and following constants are only available
983
on Windows.
984
985
.. class:: STARTUPINFO(*, dwFlags=0, hStdInput=None, hStdOutput=None, \
986
hStdError=None, wShowWindow=0, lpAttributeList=None)
987
988
Partial support of the Windows
989
`STARTUPINFO <https://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx>`__
990
structure is used for :class:`Popen` creation. The following attributes can
991
be set by passing them as keyword-only arguments.
992
993
.. versionchanged:: 3.7
994
Keyword-only argument support was added.
995
996
.. attribute:: dwFlags
997
998
A bit field that determines whether certain :class:`STARTUPINFO`
999
attributes are used when the process creates a window. ::
1000