Skip to content

Latest commit

 

History

History
1634 lines (1139 loc) · 60.5 KB

subprocess.rst

File metadata and controls

1634 lines (1139 loc) · 60.5 KB
 
May 8, 2024
May 8, 2024
1
:mod:`!subprocess` --- Subprocess management
2
============================================
Aug 15, 2007
Aug 15, 2007
3
4
.. module:: subprocess
5
:synopsis: Subprocess management.
Jun 11, 2016
Jun 11, 2016
6
7
**Source code:** :source:`Lib/subprocess.py`
8
9
--------------
Aug 15, 2007
Aug 15, 2007
10
Feb 6, 2026
Feb 6, 2026
11
The :mod:`!subprocess` module allows you to spawn new processes, connect to their
Aug 15, 2007
Aug 15, 2007
12
input/output/error pipes, and obtain their return codes. This module intends to
Mar 13, 2014
Mar 13, 2014
13
replace several older modules and functions::
Aug 15, 2007
Aug 15, 2007
14
15
os.system
16
os.spawn*
17
Feb 6, 2026
Feb 6, 2026
18
Information about how the :mod:`!subprocess` module can be used to replace these
Aug 15, 2007
Aug 15, 2007
19
modules and functions can be found in the following sections.
20
Jul 2, 2008
Jul 2, 2008
21
.. seealso::
22
23
:pep:`324` -- PEP proposing the subprocess module
24
Sep 23, 2024
Sep 23, 2024
25
.. include:: ../includes/wasm-mobile-notavail.rst
Aug 15, 2007
Aug 15, 2007
26
Feb 6, 2026
Feb 6, 2026
27
Using the :mod:`!subprocess` Module
28
-----------------------------------
Aug 15, 2007
Aug 15, 2007
29
Apr 14, 2015
Apr 14, 2015
30
The recommended approach to invoking subprocesses is to use the :func:`run`
Apr 15, 2015
Apr 15, 2015
31
function for all use cases it can handle. For more advanced use cases, the
32
underlying :class:`Popen` interface can be used directly.
Nov 8, 2011
Nov 8, 2011
33
Apr 14, 2015
Apr 14, 2015
34
35
.. function:: run(args, *, stdin=None, input=None, stdout=None, stderr=None,\
Aug 9, 2018
Aug 9, 2018
36
capture_output=False, shell=False, cwd=None, timeout=None, \
Nov 12, 2018
Nov 12, 2018
37
check=False, encoding=None, errors=None, text=None, env=None, \
May 17, 2020
May 17, 2020
38
universal_newlines=None, **other_popen_kwargs)
Nov 8, 2011
Nov 8, 2011
39
40
Run the command described by *args*. Wait for command to complete, then
Apr 14, 2015
Apr 14, 2015
41
return a :class:`CompletedProcess` instance.
Nov 8, 2011
Nov 8, 2011
42
43
The arguments shown above are merely the most common ones, described below
Nov 8, 2011
Nov 8, 2011
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
Jan 30, 2018
Jan 30, 2018
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.)
Nov 8, 2011
Nov 8, 2011
49
Jan 30, 2018
Jan 30, 2018
50
If *capture_output* is true, stdout and stderr will be captured.
51
When used, the internal :class:`Popen` object is automatically created with
May 29, 2024
May 29, 2024
52
*stdout* and *stderr* both set to :data:`~subprocess.PIPE`.
Apr 1, 2024
Apr 1, 2024
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*.
Apr 14, 2015
Apr 14, 2015
58
May 25, 2023
May 25, 2023
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.
Nov 8, 2011
Nov 8, 2011
66
Apr 14, 2015
Apr 14, 2015
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
Oct 23, 2017
Oct 23, 2017
69
*encoding* or *errors* is specified or *text* is true. When
Sep 7, 2016
Sep 7, 2016
70
used, the internal :class:`Popen` object is automatically created with
Apr 1, 2024
Apr 1, 2024
71
*stdin* set to :data:`~subprocess.PIPE`,
72
and the *stdin* argument may not be used as well.
Nov 8, 2011
Nov 8, 2011
73
Oct 19, 2016
Oct 19, 2016
74
If *check* is true, and the process exits with a non-zero exit code, a
Apr 14, 2015
Apr 14, 2015
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.
Nov 8, 2011
Nov 8, 2011
78
Oct 23, 2017
Oct 23, 2017
79
If *encoding* or *errors* are specified, or *text* is true,
Sep 7, 2016
Sep 7, 2016
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.
Oct 23, 2017
Oct 23, 2017
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.
Sep 7, 2016
Sep 7, 2016
84
Jun 5, 2018
Jun 5, 2018
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
Nov 8, 2022
Nov 8, 2022
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`.
Jun 5, 2018
Jun 5, 2018
91
Nov 8, 2011
Nov 8, 2011
92
Examples::
93
Apr 14, 2015
Apr 14, 2015
94
>>> subprocess.run(["ls", "-l"]) # doesn't capture output
95
CompletedProcess(args=['ls', '-l'], returncode=0)
Nov 8, 2011
Nov 8, 2011
96
Apr 14, 2015
Apr 14, 2015
97
>>> subprocess.run("exit 1", shell=True, check=True)
Nov 8, 2011
Nov 8, 2011
98
Traceback (most recent call last):
Apr 14, 2015
Apr 14, 2015
99
...
Nov 8, 2011
Nov 8, 2011
100
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
101
Jan 30, 2018
Jan 30, 2018
102
>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
Apr 14, 2015
Apr 14, 2015
103
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
Jan 30, 2018
Jan 30, 2018
104
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
Nov 8, 2011
Nov 8, 2011
105
Apr 14, 2015
Apr 14, 2015
106
.. versionadded:: 3.5
Nov 8, 2011
Nov 8, 2011
107
Sep 7, 2016
Sep 7, 2016
108
.. versionchanged:: 3.6
109
110
Added *encoding* and *errors* parameters
111
Oct 23, 2017
Oct 23, 2017
112
.. versionchanged:: 3.7
113
Jan 30, 2018
Jan 30, 2018
114
Added the *text* parameter, as a more understandable alias of *universal_newlines*.
115
Added the *capture_output* parameter.
Oct 23, 2017
Oct 23, 2017
116
Feb 9, 2023
Feb 9, 2023
117
.. versionchanged:: 3.12
Feb 8, 2023
Feb 8, 2023
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
Apr 14, 2015
Apr 14, 2015
125
.. class:: CompletedProcess
Nov 8, 2011
Nov 8, 2011
126
Apr 14, 2015
Apr 14, 2015
127
The return value from :func:`run`, representing a process that has finished.
Nov 8, 2011
Nov 8, 2011
128
Apr 14, 2015
Apr 14, 2015
129
.. attribute:: args
Nov 8, 2011
Nov 8, 2011
130
Apr 14, 2015
Apr 14, 2015
131
The arguments used to launch the process. This may be a list or a string.
Nov 8, 2011
Nov 8, 2011
132
Apr 14, 2015
Apr 14, 2015
133
.. attribute:: returncode
Nov 8, 2011
Nov 8, 2011
134
Apr 14, 2015
Apr 14, 2015
135
Exit status of the child process. Typically, an exit status of 0 indicates
136
that it ran successfully.
Nov 8, 2011
Nov 8, 2011
137
Apr 14, 2015
Apr 14, 2015
138
A negative value ``-N`` indicates that the child was terminated by signal
139
``N`` (POSIX only).
Nov 8, 2011
Nov 8, 2011
140
Apr 14, 2015
Apr 14, 2015
141
.. attribute:: stdout
Apr 22, 2013
Apr 22, 2013
142
Apr 14, 2015
Apr 14, 2015
143
Captured stdout from the child process. A bytes sequence, or a string if
Oct 23, 2017
Oct 23, 2017
144
:func:`run` was called with an encoding, errors, or text=True.
145
``None`` if stdout was not captured.
Nov 8, 2011
Nov 8, 2011
146
Apr 14, 2015
Apr 14, 2015
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
Oct 19, 2016
Oct 19, 2016
149
``None``.
Nov 8, 2011
Nov 8, 2011
150
Apr 14, 2015
Apr 14, 2015
151
.. attribute:: stderr
Nov 8, 2011
Nov 8, 2011
152
Apr 14, 2015
Apr 14, 2015
153
Captured stderr from the child process. A bytes sequence, or a string if
Oct 23, 2017
Oct 23, 2017
154
:func:`run` was called with an encoding, errors, or text=True.
155
``None`` if stderr was not captured.
Apr 22, 2013
Apr 22, 2013
156
Apr 14, 2015
Apr 14, 2015
157
.. method:: check_returncode()
Nov 8, 2011
Nov 8, 2011
158
Apr 14, 2015
Apr 14, 2015
159
If :attr:`returncode` is non-zero, raise a :exc:`CalledProcessError`.
Nov 8, 2011
Nov 8, 2011
160
Apr 14, 2015
Apr 14, 2015
161
.. versionadded:: 3.5
Nov 8, 2011
Nov 8, 2011
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
Nov 8, 2011
Nov 8, 2011
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
May 11, 2014
May 11, 2014
176
opened. Most useful with :meth:`Popen.communicate`.
Nov 8, 2011
Nov 8, 2011
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
Aug 9, 2012
Aug 9, 2012
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
Apr 14, 2015
Apr 14, 2015
208
Output of the child process if it was captured by :func:`run` or
Sep 30, 2022
Sep 30, 2022
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.
Aug 9, 2012
Aug 9, 2012
213
Apr 14, 2015
Apr 14, 2015
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`.
Sep 30, 2022
Sep 30, 2022
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.
Apr 14, 2015
Apr 14, 2015
224
Aug 9, 2012
Aug 9, 2012
225
.. versionadded:: 3.3
226
Apr 14, 2015
Apr 14, 2015
227
.. versionchanged:: 3.5
228
*stdout* and *stderr* attributes added
Aug 9, 2012
Aug 9, 2012
229
230
.. exception:: CalledProcessError
231
232
Subclass of :exc:`SubprocessError`, raised when a process run by
Apr 30, 2022
Apr 30, 2022
233
:func:`check_call`, :func:`check_output`, or :func:`run` (with ``check=True``)
234
returns a non-zero exit status.
235
Aug 9, 2012
Aug 9, 2012
236
237
.. attribute:: returncode
238
Aug 7, 2026
Aug 7, 2026
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.
Aug 9, 2012
Aug 9, 2012
241
242
.. attribute:: cmd
243
244
Command that was used to spawn the child process.
245
246
.. attribute:: output
247
Apr 14, 2015
Apr 14, 2015
248
Output of the child process if it was captured by :func:`run` or
Aug 9, 2012
Aug 9, 2012
249
:func:`check_output`. Otherwise, ``None``.
250
Apr 14, 2015
Apr 14, 2015
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
Aug 9, 2012
Aug 9, 2012
262
263
Nov 8, 2011
Nov 8, 2011
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
Jan 20, 2023
Jan 20, 2023
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*.
Nov 8, 2011
Nov 8, 2011
292
Aug 15, 2012
Aug 15, 2012
293
.. index::
294
single: universal newlines; subprocess module
295
Feb 11, 2018
Feb 11, 2018
296
If *encoding* or *errors* are specified, or *text* (also known as
297
*universal_newlines*) is true,
Sep 7, 2016
Sep 7, 2016
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`.
Jul 7, 2013
Jul 7, 2013
301
Sep 7, 2016
Sep 7, 2016
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
Jan 22, 2024
Jan 22, 2024
311
.. versionchanged:: 3.6
312
Added the *encoding* and *errors* parameters.
Nov 8, 2011
Nov 8, 2011
313
Jan 22, 2024
Jan 22, 2024
314
.. versionchanged:: 3.7
Feb 11, 2018
Feb 11, 2018
315
Added the *text* parameter as an alias for *universal_newlines*.
316
Aug 13, 2012
Aug 13, 2012
317
.. note::
318
Mar 21, 2013
Mar 21, 2013
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.
Aug 13, 2012
Aug 13, 2012
322
323
If *shell* is ``True``, the specified command will be executed through
Sep 15, 2012
Sep 15, 2012
324
the shell. This can be useful if you are using Python primarily for the
Nov 8, 2011
Nov 8, 2011
325
enhanced control flow it offers over most system shells and still want
Sep 15, 2012
Sep 15, 2012
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`).
Nov 8, 2011
Nov 8, 2011
332
Aug 13, 2012
Aug 13, 2012
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
May 11, 2014
May 11, 2014
339
.. note::
Nov 8, 2011
Nov 8, 2011
340
May 11, 2014
May 11, 2014
341
Read the `Security Considerations`_ section before using ``shell=True``.
Oct 28, 2012
Oct 28, 2012
342
Nov 8, 2011
Nov 8, 2011
343
These options, along with all of the other options, are described in more
344
detail in the :class:`Popen` constructor documentation.
345
346
Dec 25, 2011
Dec 25, 2011
347
Popen Constructor
Dec 25, 2011
Dec 25, 2011
348
^^^^^^^^^^^^^^^^^
Nov 8, 2011
Nov 8, 2011
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.
Aug 15, 2007
Aug 15, 2007
354
355
Mar 23, 2013
Mar 23, 2013
356
.. class:: Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, \
Oct 11, 2012
Oct 11, 2012
357
stderr=None, preexec_fn=None, close_fds=True, shell=False, \
Nov 12, 2018
Nov 12, 2018
358
cwd=None, env=None, universal_newlines=None, \
Oct 11, 2012
Oct 11, 2012
359
startupinfo=None, creationflags=0, restore_signals=True, \
Dec 17, 2020
Dec 17, 2020
360
start_new_session=False, pass_fds=(), *, group=None, \
Oct 12, 2019
Oct 12, 2019
361
extra_groups=None, user=None, umask=-1, \
May 5, 2022
May 5, 2022
362
encoding=None, errors=None, text=None, pipesize=-1, \
363
process_group=None)
Aug 15, 2007
Aug 15, 2007
364
May 11, 2014
May 11, 2014
365
Execute a child program in a new process. On POSIX, the class uses
Oct 20, 2020
Oct 20, 2020
366
:meth:`os.execvpe`-like behavior to execute the child program. On Windows,
Oct 11, 2012
Oct 11, 2012
367
the class uses the Windows ``CreateProcess()`` function. The arguments to
368
:class:`Popen` are as follows.
Aug 15, 2007
Aug 15, 2007
369
May 28, 2019
May 28, 2019
370
*args* should be a sequence of program arguments or else a single string
371
or :term:`path-like object`.
Feb 27, 2018
Feb 27, 2018
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.
Oct 9, 2012
Oct 9, 2012
377
Oct 20, 2020
Oct 20, 2020
378
.. warning::
379
Jul 5, 2022
Jul 5, 2022
380
For maximum reliability, use a fully qualified path for the executable.
Oct 20, 2020
Oct 20, 2020
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
Feb 10, 2020
Feb 10, 2020
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
May 11, 2014
May 11, 2014
402
On POSIX, if *args* is a string, the string is interpreted as the name or
Oct 11, 2012
Oct 11, 2012
403
path of the program to execute. However, this can only be done if not
404
passing arguments to the program.
Feb 4, 2010
Feb 4, 2010
405
406
.. note::
407
Feb 10, 2020
Feb 10, 2020
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*::
Feb 4, 2010
Feb 4, 2010
411
412
>>> import shlex, subprocess
Feb 5, 2010
Feb 5, 2010
413
>>> command_line = input()
Feb 4, 2010
Feb 4, 2010
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
Oct 11, 2012
Oct 11, 2012
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.
Oct 9, 2012
Oct 9, 2012
429
May 28, 2019
May 28, 2019
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
Oct 19, 2016
Oct 19, 2016
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
Oct 11, 2012
Oct 11, 2012
441
recommended to pass *args* as a string rather than as a sequence.
Oct 9, 2012
Oct 9, 2012
442
May 11, 2014
May 11, 2014
443
On POSIX with ``shell=True``, the shell defaults to :file:`/bin/sh`. If
Oct 9, 2012
Oct 9, 2012
444
*args* is a string, the string specifies the command
445
to execute through the shell. This means that the string must be
Feb 4, 2010
Feb 4, 2010
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
Oct 9, 2012
Oct 9, 2012
450
itself. That is to say, :class:`Popen` does the equivalent of::
Feb 4, 2010
Feb 4, 2010
451
452
Popen(['/bin/sh', '-c', args[0], args[1], ...])
Aug 15, 2007
Aug 15, 2007
453
Oct 9, 2012
Oct 9, 2012
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.
Aug 15, 2007
Aug 15, 2007
459
May 11, 2014
May 11, 2014
460
.. note::
Oct 11, 2012
Oct 11, 2012
461
May 11, 2014
May 11, 2014
462
Read the `Security Considerations`_ section before using ``shell=True``.
Oct 11, 2012
Oct 11, 2012
463
Sep 21, 2014
Sep 21, 2014
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
Jul 28, 2023
Jul 28, 2023
468
- ``0`` means unbuffered (read and write are one
Sep 21, 2014
Sep 21, 2014
469
system call and can return short)
Jul 28, 2023
Jul 28, 2023
470
- ``1`` means line buffered
Feb 8, 2023
Feb 8, 2023
471
(only usable if ``text=True`` or ``universal_newlines=True``)
Sep 21, 2014
Sep 21, 2014
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.
Aug 15, 2007
Aug 15, 2007
476
Nov 25, 2013
Nov 25, 2013
477
.. versionchanged:: 3.3.1
Mar 23, 2013
Mar 23, 2013
478
*bufsize* now defaults to -1 to enable buffering by default to match the
Nov 25, 2013
Nov 25, 2013
479
behavior that most code expects. In versions prior to Python 3.2.4 and
Jul 28, 2023
Jul 28, 2023
480
3.3.1 it incorrectly defaulted to ``0`` which was unbuffered
Nov 25, 2013
Nov 25, 2013
481
and allowed short reads. This was unintentional and did not match the
482
behavior of Python 2 as most code expected.
Jun 2, 2010
Jun 2, 2010
483
Oct 9, 2012
Oct 9, 2012
484
The *executable* argument specifies a replacement program to execute. It
485
is very seldom needed. When ``shell=False``, *executable* replaces the
Oct 11, 2012
Oct 11, 2012
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
May 11, 2014
May 11, 2014
489
actually executed. On POSIX, the *args* name
Oct 9, 2012
Oct 9, 2012
490
becomes the display name for the executable in utilities such as
May 11, 2014
May 11, 2014
491
:program:`ps`. If ``shell=True``, on POSIX the *executable* argument
Oct 9, 2012
Oct 9, 2012
492
specifies a replacement shell for the default :file:`/bin/sh`.
Aug 15, 2007
Aug 15, 2007
493
May 28, 2019
May 28, 2019
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
Feb 9, 2023
Feb 9, 2023
501
.. versionchanged:: 3.12
Feb 8, 2023
Feb 8, 2023
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
Nov 8, 2011
Nov 8, 2011
509
*stdin*, *stdout* and *stderr* specify the executed program's standard input,
Dec 7, 2008
Dec 7, 2008
510
standard output and standard error file handles, respectively. Valid values
Jan 20, 2023
Jan 20, 2023
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
Feb 25, 2022
Feb 25, 2022
517
that the stderr data from the applications should be captured into the same
Jan 20, 2023
Jan 20, 2023
518
file handle as for *stdout*.
Aug 15, 2007
Aug 15, 2007
519
520
If *preexec_fn* is set to a callable object, this object will be called in the
Mar 14, 2010
Mar 14, 2010
521
child process just before the child is executed.
May 11, 2014
May 11, 2014
522
(POSIX only)
Mar 14, 2010
Mar 14, 2010
523
524
.. warning::
525
May 5, 2022
May 5, 2022
526
The *preexec_fn* parameter is NOT SAFE to use in the presence of threads
Mar 14, 2010
Mar 14, 2010
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*.
May 5, 2022
May 5, 2022
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.
Aug 15, 2007
Aug 15, 2007
536
Aug 27, 2019
Aug 27, 2019
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
Jul 28, 2023
Jul 28, 2023
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
Mar 25, 2018
Mar 25, 2018
546
when *close_fds* is false, file descriptors obey their inheritable flag
547
as described in :ref:`fd_inheritance`.
548
Dec 4, 2010
Dec 4, 2010
549
On Windows, if *close_fds* is true then no handles will be inherited by the
Dec 18, 2017
Dec 18, 2017
550
child process unless explicitly passed in the ``handle_list`` element of
551
:attr:`STARTUPINFO.lpAttributeList`, or by standard handle redirection.
Aug 15, 2007
Aug 15, 2007
552
Dec 14, 2010
Dec 14, 2010
553
.. versionchanged:: 3.2
554
The default for *close_fds* was changed from :const:`False` to
555
what is described above.
556
Dec 18, 2017
Dec 18, 2017
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
Dec 14, 2010
Dec 14, 2010
562
*pass_fds* is an optional sequence of file descriptors to keep open
563
between the parent and child. Providing any *pass_fds* forces
May 11, 2014
May 11, 2014
564
*close_fds* to be :const:`True`. (POSIX only)
Dec 14, 2010
Dec 14, 2010
565
Jul 6, 2018
Jul 6, 2018
566
.. versionchanged:: 3.2
Dec 14, 2010
Dec 14, 2010
567
The *pass_fds* parameter was added.
Aug 15, 2007
Aug 15, 2007
568
Sep 30, 2012
Sep 30, 2012
569
If *cwd* is not ``None``, the function changes the working directory to
May 28, 2019
May 28, 2019
570
*cwd* before executing the child. *cwd* can be a string, bytes or
Apr 17, 2021
Apr 17, 2021
571
:term:`path-like <path-like object>` object. On POSIX, the function
Feb 26, 2017
Feb 26, 2017
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
May 28, 2019
May 28, 2019
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.
Aug 15, 2007
Aug 15, 2007
583
Nov 29, 2013
Nov 29, 2013
584
If *restore_signals* is true (the default) all signals that Python has set to
Mar 14, 2010
Mar 14, 2010
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.
May 11, 2014
May 11, 2014
587
(POSIX only)
Mar 14, 2010
Mar 14, 2010
588
589
.. versionchanged:: 3.2
590
*restore_signals* was added.
591
May 5, 2022
May 5, 2022
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.
Mar 14, 2010
Mar 14, 2010
594
May 5, 2022
May 5, 2022
595
.. availability:: POSIX
Mar 14, 2010
Mar 14, 2010
596
.. versionchanged:: 3.2
597
*start_new_session* was added.
598
May 5, 2022
May 5, 2022
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
Sep 12, 2019
Sep 12, 2019
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
Aug 30, 2024
Aug 30, 2024
608
value is a string, it will be looked up via :func:`grp.getgrnam` and
Sep 12, 2019
Sep 12, 2019
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
Aug 30, 2024
Aug 30, 2024
618
:func:`grp.getgrnam` and the values in ``gr_gid`` will be used.
Sep 12, 2019
Sep 12, 2019
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
Aug 30, 2024
Aug 30, 2024
626
value is a string, it will be looked up via :func:`pwd.getpwnam` and
Sep 12, 2019
Sep 12, 2019
627
the value in ``pw_uid`` will be used. If the value is an integer, it will
628
be passed verbatim. (POSIX only)
629
Apr 5, 2026
Apr 5, 2026
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
Sep 12, 2019
Sep 12, 2019
636
.. availability:: POSIX
637
.. versionadded:: 3.9
638
Oct 12, 2019
Oct 12, 2019
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
Apr 20, 2008
Apr 20, 2008
645
If *env* is not ``None``, it must be a mapping that defines the environment
Mar 14, 2010
Mar 14, 2010
646
variables for the new process; these are used instead of the default
Nov 8, 2022
Nov 8, 2022
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`.
Aug 15, 2007
Aug 15, 2007
650
Apr 16, 2009
Apr 16, 2009
651
.. note::
Apr 15, 2009
Apr 15, 2009
652
Dec 20, 2009
Dec 20, 2009
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
Oct 8, 2025
Oct 8, 2025
655
specified *env* **must** include a valid ``%SystemRoot%``.
Apr 15, 2009
Apr 15, 2009
656
Feb 26, 2016
Feb 26, 2016
657
.. _side-by-side assembly: https://en.wikipedia.org/wiki/Side-by-Side_Assembly
Apr 16, 2009
Apr 16, 2009
658
Feb 11, 2018
Feb 11, 2018
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
Apr 30, 2022
Apr 30, 2022
661
*encoding* and *errors*, as described above in :ref:`frequently-used-arguments`.
Feb 11, 2018
Feb 11, 2018
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.
Sep 7, 2016
Sep 7, 2016
664
665
.. versionadded:: 3.6
666
*encoding* and *errors* were added.
Aug 15, 2007
Aug 15, 2007
667
Feb 11, 2018
Feb 11, 2018
668
.. versionadded:: 3.7
669
*text* was added as a more readable alias for *universal_newlines*.
670
Apr 30, 2011
Apr 30, 2011
671
If given, *startupinfo* will be a :class:`STARTUPINFO` object, which is
672
passed to the underlying ``CreateProcess`` function.
Feb 2, 2024
Feb 2, 2024
673
674
If given, *creationflags*, can be one or more of the following flags:
Nov 8, 2017
Nov 8, 2017
675
Oct 11, 2023
Oct 11, 2023
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`
Aug 15, 2007
Aug 15, 2007
688
Oct 19, 2020
Oct 19, 2020
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
Jan 22, 2024
Jan 22, 2024
694
.. versionchanged:: 3.10
695
Added the *pipesize* parameter.
Oct 19, 2020
Oct 19, 2020
696
May 12, 2011
May 12, 2011
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.
Dec 3, 2010
Dec 3, 2010
699
::
700
701
with Popen(["ifconfig"], stdout=PIPE) as proc:
702
log.write(proc.stdout.read())
703
Jun 27, 2019
Jun 27, 2019
704
.. audit-event:: subprocess.Popen executable,args,cwd,env subprocess.Popen
Jun 24, 2019
Jun 24, 2019
705
706
Popen and the other functions in this module that use it raise an
707
:ref:`auditing event <auditing>` ``subprocess.Popen`` with arguments
Nov 19, 2019
Nov 19, 2019
708
``executable``, ``args``, ``cwd``, and ``env``. The value for ``args``
Jun 24, 2019
Jun 24, 2019
709
may be a single string or a list of strings, depending on platform.
710
Dec 3, 2010
Dec 3, 2010
711
.. versionchanged:: 3.2
712
Added context manager support.
713
May 20, 2016
May 20, 2016
714
.. versionchanged:: 3.6
715
Popen destructor now emits a :exc:`ResourceWarning` warning if the child
716
process is still running.
717
Apr 25, 2019
Apr 25, 2019
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
Aug 15, 2007
Aug 15, 2007
725
726
Exceptions
727
^^^^^^^^^^
728
729
Exceptions raised in the child process, before the new program has started to
Jan 3, 2019
Jan 3, 2019
730
execute, will be re-raised in the parent.
Aug 15, 2007
Aug 15, 2007
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
Jul 22, 2021
Jul 22, 2021
734
:exc:`OSError` exceptions. Note that, when ``shell=True``, :exc:`OSError`
Jul 22, 2021
Jul 22, 2021
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.
Aug 15, 2007
Aug 15, 2007
738
739
A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid
740
arguments.
741
Nov 8, 2011
Nov 8, 2011
742
:func:`check_call` and :func:`check_output` will raise
743
:exc:`CalledProcessError` if the called process returns a non-zero return
744
code.
Aug 15, 2007
Aug 15, 2007
745
Mar 14, 2011
Mar 14, 2011
746
All of the functions and methods that accept a *timeout* parameter, such as
May 25, 2023
May 25, 2023
747
:func:`run` and :meth:`Popen.communicate` will raise :exc:`TimeoutExpired` if
Mar 14, 2011
Mar 14, 2011
748
the timeout expires before the process exits.
749
Mar 16, 2011
Mar 16, 2011
750
Exceptions defined in this module all inherit from :exc:`SubprocessError`.
Mar 14, 2011
Mar 14, 2011
751
Oct 11, 2023
Oct 11, 2023
752
.. versionadded:: 3.3
753
The :exc:`SubprocessError` base class was added.
Mar 14, 2011
Mar 14, 2011
754
Aug 9, 2021
Aug 9, 2021
755
.. _subprocess-security:
Aug 15, 2007
Aug 15, 2007
756
May 11, 2014
May 11, 2014
757
Security Considerations
758
-----------------------
759
Apr 17, 2024
Apr 17, 2024
760
Unlike some other popen functions, this library will not
761
implicitly choose to call a system shell. This means that all characters,
May 11, 2014
May 11, 2014
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
Feb 26, 2016
Feb 26, 2016
766
`shell injection <https://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_
Nov 11, 2020
Nov 11, 2020
767
vulnerabilities. On :ref:`some platforms <shlex-quote-warning>`, it is possible
768
to use :func:`shlex.quote` for this escaping.
Aug 15, 2007
Aug 15, 2007
769
Apr 17, 2024
Apr 17, 2024
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
Aug 15, 2007
Aug 15, 2007
778
779
Popen Objects
780
-------------
781
782
Instances of the :class:`Popen` class have the following methods:
783
784
785
.. method:: Popen.poll()
786
Aug 23, 2013
Aug 23, 2013
787
Check if child process has terminated. Set and return
Aug 29, 2017
Aug 29, 2017
788
:attr:`~Popen.returncode` attribute. Otherwise, returns ``None``.
Aug 15, 2007
Aug 15, 2007
789
790
Mar 14, 2011
Mar 14, 2011
791
.. method:: Popen.wait(timeout=None)
Aug 15, 2007
Aug 15, 2007
792
Aug 23, 2013
Aug 23, 2013
793
Wait for child process to terminate. Set and return
794
:attr:`~Popen.returncode` attribute.
Aug 15, 2007
Aug 15, 2007
795
Mar 14, 2011
Mar 14, 2011
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
May 11, 2014
May 11, 2014
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
Feb 24, 2014
Feb 24, 2014
807
.. note::
808
Jan 28, 2026
Jan 28, 2026
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
Nov 16, 2023
Nov 16, 2023
823
:class:`asyncio.create_subprocess_exec`.
Feb 24, 2014
Feb 24, 2014
824
Mar 14, 2011
Mar 14, 2011
825
.. versionchanged:: 3.3
Mar 14, 2011
Mar 14, 2011
826
*timeout* was added.
Aug 15, 2007
Aug 15, 2007
827
Jan 28, 2026
Jan 28, 2026
828
.. versionchanged:: 3.15
829
if *timeout* is not ``None``, use efficient event-driven implementation
830
on Linux >= 5.3 and macOS / BSD.
831
Mar 14, 2011
Mar 14, 2011
832
.. method:: Popen.communicate(input=None, timeout=None)
Aug 15, 2007
Aug 15, 2007
833
834
Interact with process: Send data to stdin. Read data from stdout and stderr,
Jun 24, 2020
Jun 24, 2020
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.
Aug 15, 2007
Aug 15, 2007
840
Oct 13, 2014
Oct 13, 2014
841
:meth:`communicate` returns a tuple ``(stdout_data, stderr_data)``.
Sep 7, 2016
Sep 7, 2016
842
The data will be strings if streams were opened in text mode; otherwise,
843
bytes.
Aug 15, 2007
Aug 15, 2007
844
Nov 26, 2007
Nov 26, 2007
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
Mar 14, 2011
Mar 14, 2011
850
If the process does not terminate after *timeout* seconds, a
851
:exc:`TimeoutExpired` exception will be raised. Catching this exception and
Nov 29, 2025
Nov 29, 2025
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.
Mar 14, 2011
Mar 14, 2011
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
Dec 1, 2025
Dec 1, 2025
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
Jan 6, 2008
Jan 6, 2008
872
.. note::
Aug 15, 2007
Aug 15, 2007
873
Jan 6, 2008
Jan 6, 2008
874
The data read is buffered in memory, so do not use this method if the data
875
size is large or unlimited.
Aug 15, 2007
Aug 15, 2007
876
Mar 14, 2011
Mar 14, 2011
877
.. versionchanged:: 3.3
Mar 14, 2011
Mar 14, 2011
878
*timeout* was added.
879
Aug 15, 2007
Aug 15, 2007
880
Apr 20, 2008
Apr 20, 2008
881
.. method:: Popen.send_signal(signal)
882
883
Sends the signal *signal* to the child.
884
Jan 15, 2020
Jan 15, 2020
885
Do nothing if the process completed.
886
Apr 20, 2008
Apr 20, 2008
887
.. note::
888
Apr 12, 2010
Apr 12, 2010
889
On Windows, SIGTERM is an alias for :meth:`terminate`. CTRL_C_EVENT and
Oct 15, 2010
Oct 15, 2010
890
CTRL_BREAK_EVENT can be sent to processes started with a *creationflags*
Oct 18, 2022
Oct 18, 2022
891
parameter which includes ``CREATE_NEW_PROCESS_GROUP``.
Apr 20, 2008
Apr 20, 2008
892
893
894
.. method:: Popen.terminate()
895
Feb 12, 2024
Feb 12, 2024
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
Apr 20, 2008
Apr 20, 2008
898
to stop the child.
899
900
901
.. method:: Popen.kill()
902
May 17, 2020
May 17, 2020
903
Kills the child. On POSIX OSs the function sends SIGKILL to the child.
Apr 20, 2008
Apr 20, 2008
904
On Windows :meth:`kill` is an alias for :meth:`terminate`.
905
906
Feb 8, 2023
Feb 8, 2023
907
The following attributes are also set by the class for you to access.
908
Reassigning them to new values is unsupported:
Aug 15, 2007
Aug 15, 2007
909
Apr 29, 2014
Apr 29, 2014
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
Aug 12, 2008
Aug 12, 2008
916
Aug 15, 2007
Aug 15, 2007
917
.. attribute:: Popen.stdin
918
Jan 18, 2014
Jan 18, 2014
919
If the *stdin* argument was :data:`PIPE`, this attribute is a writeable
Sep 7, 2016
Sep 7, 2016
920
stream object as returned by :func:`open`. If the *encoding* or *errors*
Feb 8, 2023
Feb 8, 2023
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``.
Aug 15, 2007
Aug 15, 2007
924
925
926
.. attribute:: Popen.stdout
927
Jan 18, 2014
Jan 18, 2014
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
Sep 7, 2016
Sep 7, 2016
930
output from the child process. If the *encoding* or *errors* arguments were
Feb 8, 2023
Feb 8, 2023
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``.
Jan 18, 2014
Jan 18, 2014
934
Aug 15, 2007
Aug 15, 2007
935
936
.. attribute:: Popen.stderr
937
Jan 18, 2014
Jan 18, 2014
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
Sep 7, 2016
Sep 7, 2016
940
error output from the child process. If the *encoding* or *errors* arguments
Feb 8, 2023
Feb 8, 2023
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``.
Aug 15, 2007
Aug 15, 2007
944
May 11, 2014
May 11, 2014
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
Aug 15, 2007
Aug 15, 2007
952
953
.. attribute:: Popen.pid
954
955
The process ID of the child process.
956
Mar 21, 2010
Mar 21, 2010
957
Note that if you set the *shell* argument to ``True``, this is the process ID
958
of the spawned shell.
959
Aug 15, 2007
Aug 15, 2007
960
961
.. attribute:: Popen.returncode
962
Apr 24, 2023
Apr 24, 2023
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.
Jan 3, 2009
Jan 3, 2009
969
Jan 6, 2008
Jan 6, 2008
970
A negative value ``-N`` indicates that the child was terminated by signal
May 11, 2014
May 11, 2014
971
``N`` (POSIX only).
Aug 15, 2007
Aug 15, 2007
972
Mar 21, 2026
Mar 21, 2026
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
Aug 15, 2007
Aug 15, 2007
978
Apr 30, 2011
Apr 30, 2011
979
Windows Popen Helpers
980
---------------------
981
982
The :class:`STARTUPINFO` class and following constants are only available
983
on Windows.
984
Mar 1, 2017
Mar 1, 2017
985
.. class:: STARTUPINFO(*, dwFlags=0, hStdInput=None, hStdOutput=None, \
Dec 18, 2017
Dec 18, 2017
986
hStdError=None, wShowWindow=0, lpAttributeList=None)
Apr 30, 2011
Apr 30, 2011
987
Apr 30, 2011
Apr 30, 2011
988
Partial support of the Windows
Feb 26, 2016
Feb 26, 2016
989
`STARTUPINFO <https://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx>`__
Mar 1, 2017
Mar 1, 2017
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.
Apr 30, 2011
Apr 30, 2011
995
996
.. attribute:: dwFlags
997
Jul 4, 2011
Jul 4, 2011
998
A bit field that determines whether certain :class:`STARTUPINFO`
999
attributes are used when the process creates a window. ::
Apr 30, 2011
Apr 30, 2011
1000