blob: efd25d1de27b9d293e4b76337291935f54098412 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`subprocess` --- Subprocess management
2===========================================
3
4.. module:: subprocess
5 :synopsis: Subprocess management.
6.. moduleauthor:: Peter Åstrand <astrand@lysator.liu.se>
7.. sectionauthor:: Peter Åstrand <astrand@lysator.liu.se>
8
9
Georg Brandl116aa622007-08-15 14:28:22 +000010The :mod:`subprocess` module allows you to spawn new processes, connect to their
11input/output/error pipes, and obtain their return codes. This module intends to
12replace several other, older modules and functions, such as::
13
14 os.system
15 os.spawn*
Georg Brandl116aa622007-08-15 14:28:22 +000016
17Information about how the :mod:`subprocess` module can be used to replace these
18modules and functions can be found in the following sections.
19
Benjamin Peterson41181742008-07-02 20:22:54 +000020.. seealso::
21
22 :pep:`324` -- PEP proposing the subprocess module
23
Georg Brandl116aa622007-08-15 14:28:22 +000024
25Using the subprocess Module
26---------------------------
27
Nick Coghlanc29248f2011-11-08 20:49:23 +100028The recommended approach to invoking subprocesses is to use the following
29convenience functions for all use cases they can handle. For more advanced
30use cases, the underlying :class:`Popen` interface can be used directly.
31
32
33.. function:: call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
34
35 Run the command described by *args*. Wait for command to complete, then
36 return the :attr:`returncode` attribute.
37
38 The arguments shown above are merely the most common ones, described below
39 in :ref:`frequently-used-arguments` (hence the slightly odd notation in
40 the abbreviated signature). The full function signature is the same as
41 that of the :class:`Popen` constructor - this functions passes all
42 supplied arguments directly through to that interface.
43
44 Examples::
45
46 >>> subprocess.call(["ls", "-l"])
47 0
48
49 >>> subprocess.call("exit 1", shell=True)
50 1
51
52 .. warning::
53
54 Invoking the system shell with ``shell=True`` can be a security hazard
55 if combined with untrusted input. See the warning under
56 :ref:`frequently-used-arguments` for details.
57
58 .. note::
59
60 Do not use ``stdout=PIPE`` or ``stderr=PIPE`` with this function. As
61 the pipes are not being read in the current process, the child
62 process may block if it generates enough output to a pipe to fill up
63 the OS pipe buffer.
64
65
66.. function:: check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
67
68 Run command with arguments. Wait for command to complete. If the return
69 code was zero then return, otherwise raise :exc:`CalledProcessError`. The
70 :exc:`CalledProcessError` object will have the return code in the
71 :attr:`returncode` attribute.
72
73 The arguments shown above are merely the most common ones, described below
74 in :ref:`frequently-used-arguments` (hence the slightly odd notation in
75 the abbreviated signature). The full function signature is the same as
76 that of the :class:`Popen` constructor - this functions passes all
77 supplied arguments directly through to that interface.
78
79 Examples::
80
81 >>> subprocess.check_call(["ls", "-l"])
82 0
83
84 >>> subprocess.check_call("exit 1", shell=True)
85 Traceback (most recent call last):
86 ...
87 subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
88
89 .. versionadded:: 2.5
90
91 .. warning::
92
93 Invoking the system shell with ``shell=True`` can be a security hazard
94 if combined with untrusted input. See the warning under
95 :ref:`frequently-used-arguments` for details.
96
97 .. note::
98
99 Do not use ``stdout=PIPE`` or ``stderr=PIPE`` with this function. As
100 the pipes are not being read in the current process, the child
101 process may block if it generates enough output to a pipe to fill up
102 the OS pipe buffer.
103
104
105.. function:: check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
106
107 Run command with arguments and return its output as a byte string.
108
109 If the return code was non-zero it raises a :exc:`CalledProcessError`. The
110 :exc:`CalledProcessError` object will have the return code in the
111 :attr:`returncode` attribute and any output in the :attr:`output`
112 attribute.
113
114 The arguments shown above are merely the most common ones, described below
115 in :ref:`frequently-used-arguments` (hence the slightly odd notation in
116 the abbreviated signature). The full function signature is largely the
117 same as that of the :class:`Popen` constructor, except that *stdout* is
118 not permitted as it is used internally. All other supplied arguments are
119 passed directly through to the :class:`Popen` constructor.
120
121 Examples::
122
123 >>> subprocess.check_output(["echo", "Hello World!"])
124 b'Hello World!\n'
125
126 >>> subprocess.check_output(["echo", "Hello World!"], universal_newlines=True)
127 'Hello World!\n'
128
129 >>> subprocess.check_output("exit 1", shell=True)
130 Traceback (most recent call last):
131 ...
132 subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
133
134 By default, this function will return the data as encoded bytes. The actual
135 encoding of the output data may depend on the command being invoked, so the
136 decoding to text will often need to be handled at the application level.
137
138 This behaviour may be overridden by setting *universal_newlines* to
139 :const:`True` as described below in :ref:`frequently-used-arguments`.
140
141 To also capture standard error in the result, use
142 ``stderr=subprocess.STDOUT``::
143
144 >>> subprocess.check_output(
145 ... "ls non_existent_file; exit 0",
146 ... stderr=subprocess.STDOUT,
147 ... shell=True)
148 'ls: non_existent_file: No such file or directory\n'
149
150 .. versionadded:: 2.7
151
152 .. warning::
153
154 Invoking the system shell with ``shell=True`` can be a security hazard
155 if combined with untrusted input. See the warning under
156 :ref:`frequently-used-arguments` for details.
157
158 .. note::
159
160 Do not use ``stderr=PIPE`` with this function. As the pipe is not being
161 read in the current process, the child process may block if it
162 generates enough output to the pipe to fill up the OS pipe buffer.
163
164
165.. data:: PIPE
166
167 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
168 to :class:`Popen` and indicates that a pipe to the standard stream should be
169 opened.
170
171
172.. data:: STDOUT
173
174 Special value that can be used as the *stderr* argument to :class:`Popen` and
175 indicates that standard error should go into the same handle as standard
176 output.
177
178
Andrew Svetloveec64202012-08-09 15:20:45 +0300179.. exception:: CalledProcessError
180
181 Exception raised when a process run by :func:`check_call` or
182 :func:`check_output` returns a non-zero exit status.
183
184 .. attribute:: returncode
185
186 Exit status of the child process.
187
188 .. attribute:: cmd
189
190 Command that was used to spawn the child process.
191
192 .. attribute:: output
193
194 Output of the child process if this exception is raised by
195 :func:`check_output`. Otherwise, ``None``.
196
197
198
Nick Coghlanc29248f2011-11-08 20:49:23 +1000199.. _frequently-used-arguments:
200
201Frequently Used Arguments
202^^^^^^^^^^^^^^^^^^^^^^^^^
203
204To support a wide variety of use cases, the :class:`Popen` constructor (and
205the convenience functions) accept a large number of optional arguments. For
206most typical use cases, many of these arguments can be safely left at their
207default values. The arguments that are most commonly needed are:
208
209 *args* is required for all calls and should be a string, or a sequence of
210 program arguments. Providing a sequence of arguments is generally
211 preferred, as it allows the module to take care of any required escaping
212 and quoting of arguments (e.g. to permit spaces in file names). If passing
213 a single string, either *shell* must be :const:`True` (see below) or else
214 the string must simply name the program to be executed without specifying
215 any arguments.
216
217 *stdin*, *stdout* and *stderr* specify the executed program's standard input,
218 standard output and standard error file handles, respectively. Valid values
219 are :data:`PIPE`, an existing file descriptor (a positive integer), an
220 existing file object, and ``None``. :data:`PIPE` indicates that a new pipe
221 to the child should be created. With the default settings of ``None``, no
222 redirection will occur; the child's file handles will be inherited from the
223 parent. Additionally, *stderr* can be :data:`STDOUT`, which indicates that
224 the stderr data from the child process should be captured into the same file
225 handle as for stdout.
226
227 When *stdout* or *stderr* are pipes and *universal_newlines* is
228 :const:`True` then the output data is assumed to be encoded as UTF-8 and
229 will automatically be decoded to text. All line endings will be converted
Georg Brandleb25fb72012-02-23 21:12:39 +0100230 to ``'\n'`` as described for the universal newlines ``'U'`` mode argument
Nick Coghlanc29248f2011-11-08 20:49:23 +1000231 to :func:`open`.
232
233 If *shell* is :const:`True`, the specified command will be executed through
234 the shell. This can be useful if you are using Python primarily for the
235 enhanced control flow it offers over most system shells and still want
236 access to other shell features such as filename wildcards, shell pipes and
237 environment variable expansion.
238
239 .. warning::
240
241 Executing shell commands that incorporate unsanitized input from an
242 untrusted source makes a program vulnerable to `shell injection
243 <http://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_,
244 a serious security flaw which can result in arbitrary command execution.
245 For this reason, the use of *shell=True* is **strongly discouraged** in cases
246 where the command string is constructed from external input::
247
248 >>> from subprocess import call
249 >>> filename = input("What file would you like to display?\n")
250 What file would you like to display?
251 non_existent; rm -rf / #
252 >>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...
253
254 ``shell=False`` disables all shell based features, but does not suffer
255 from this vulnerability; see the Note in the :class:`Popen` constructor
256 documentation for helpful hints in getting ``shell=False`` to work.
257
258These options, along with all of the other options, are described in more
259detail in the :class:`Popen` constructor documentation.
260
261
Sandro Tosi1526ad12011-12-25 11:27:37 +0100262Popen Constructor
Sandro Tosi3e6c8142011-12-25 17:14:11 +0100263^^^^^^^^^^^^^^^^^
Nick Coghlanc29248f2011-11-08 20:49:23 +1000264
265The underlying process creation and management in this module is handled by
266the :class:`Popen` class. It offers a lot of flexibility so that developers
267are able to handle the less common cases not covered by the convenience
268functions.
Georg Brandl116aa622007-08-15 14:28:22 +0000269
270
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000271.. class:: Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=())
Georg Brandl116aa622007-08-15 14:28:22 +0000272
273 Arguments are:
274
Benjamin Petersond18de0e2008-07-31 20:21:46 +0000275 *args* should be a string, or a sequence of program arguments. The program
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000276 to execute is normally the first item in the args sequence or the string if
277 a string is given, but can be explicitly set by using the *executable*
278 argument. When *executable* is given, the first item in the args sequence
279 is still treated by most programs as the command name, which can then be
280 different from the actual executable name. On Unix, it becomes the display
281 name for the executing program in utilities such as :program:`ps`.
Georg Brandl116aa622007-08-15 14:28:22 +0000282
283 On Unix, with *shell=False* (default): In this case, the Popen class uses
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000284 :meth:`os.execvp` like behavior to execute the child program.
285 *args* should normally be a
R. David Murray5973e4d2010-02-04 16:41:57 +0000286 sequence. If a string is specified for *args*, it will be used as the name
287 or path of the program to execute; this will only work if the program is
288 being given no arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000289
R. David Murray5973e4d2010-02-04 16:41:57 +0000290 .. note::
291
292 :meth:`shlex.split` can be useful when determining the correct
293 tokenization for *args*, especially in complex cases::
294
295 >>> import shlex, subprocess
R. David Murray73bc75b2010-02-05 16:25:12 +0000296 >>> command_line = input()
R. David Murray5973e4d2010-02-04 16:41:57 +0000297 /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
298 >>> args = shlex.split(command_line)
299 >>> print(args)
300 ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
301 >>> p = subprocess.Popen(args) # Success!
302
303 Note in particular that options (such as *-input*) and arguments (such
304 as *eggs.txt*) that are separated by whitespace in the shell go in separate
305 list elements, while arguments that need quoting or backslash escaping when
306 used in the shell (such as filenames containing spaces or the *echo* command
307 shown above) are single list elements.
308
309 On Unix, with *shell=True*: If args is a string, it specifies the command
310 string to execute through the shell. This means that the string must be
311 formatted exactly as it would be when typed at the shell prompt. This
312 includes, for example, quoting or backslash escaping filenames with spaces in
313 them. If *args* is a sequence, the first item specifies the command string, and
314 any additional items will be treated as additional arguments to the shell
315 itself. That is to say, *Popen* does the equivalent of::
316
317 Popen(['/bin/sh', '-c', args[0], args[1], ...])
Georg Brandl116aa622007-08-15 14:28:22 +0000318
R. David Murrayc7399d02010-11-12 00:35:31 +0000319 .. warning::
320
Nick Coghlanc29248f2011-11-08 20:49:23 +1000321 Enabling this option can be a security hazard if combined with untrusted
322 input. See the warning under :ref:`frequently-used-arguments`
323 for details.
R. David Murrayc7399d02010-11-12 00:35:31 +0000324
Eli Bendersky046a7642011-04-15 07:23:26 +0300325 On Windows: the :class:`Popen` class uses CreateProcess() to execute the
326 child program, which operates on strings. If *args* is a sequence, it will
327 be converted to a string in a manner described in
328 :ref:`converting-argument-sequence`.
Georg Brandl116aa622007-08-15 14:28:22 +0000329
330 *bufsize*, if given, has the same meaning as the corresponding argument to the
331 built-in open() function: :const:`0` means unbuffered, :const:`1` means line
332 buffered, any other positive value means use a buffer of (approximately) that
333 size. A negative *bufsize* means to use the system default, which usually means
334 fully buffered. The default value for *bufsize* is :const:`0` (unbuffered).
335
Antoine Pitrou4b876202010-06-02 17:10:49 +0000336 .. note::
337
338 If you experience performance issues, it is recommended that you try to
339 enable buffering by setting *bufsize* to either -1 or a large enough
340 positive value (such as 4096).
341
Georg Brandl116aa622007-08-15 14:28:22 +0000342 The *executable* argument specifies the program to execute. It is very seldom
343 needed: Usually, the program to execute is defined by the *args* argument. If
344 ``shell=True``, the *executable* argument specifies which shell to use. On Unix,
345 the default shell is :file:`/bin/sh`. On Windows, the default shell is
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000346 specified by the :envvar:`COMSPEC` environment variable. The only reason you
347 would need to specify ``shell=True`` on Windows is where the command you
348 wish to execute is actually built in to the shell, eg ``dir``, ``copy``.
349 You don't need ``shell=True`` to run a batch file, nor to run a console-based
350 executable.
Georg Brandl116aa622007-08-15 14:28:22 +0000351
Nick Coghlanc29248f2011-11-08 20:49:23 +1000352 *stdin*, *stdout* and *stderr* specify the executed program's standard input,
Georg Brandlaf265f42008-12-07 15:06:20 +0000353 standard output and standard error file handles, respectively. Valid values
354 are :data:`PIPE`, an existing file descriptor (a positive integer), an
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000355 existing :term:`file object`, and ``None``. :data:`PIPE` indicates that a
Nick Coghlanc29248f2011-11-08 20:49:23 +1000356 new pipe to the child should be created. With the default settings of
357 ``None``, no redirection will occur; the child's file handles will be
358 inherited from the parent. Additionally, *stderr* can be :data:`STDOUT`,
359 which indicates that the stderr data from the applications should be
360 captured into the same file handle as for stdout.
Georg Brandl116aa622007-08-15 14:28:22 +0000361
362 If *preexec_fn* is set to a callable object, this object will be called in the
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000363 child process just before the child is executed.
364 (Unix only)
365
366 .. warning::
367
368 The *preexec_fn* parameter is not safe to use in the presence of threads
369 in your application. The child process could deadlock before exec is
370 called.
371 If you must use it, keep it trivial! Minimize the number of libraries
372 you call into.
373
374 .. note::
375
376 If you need to modify the environment for the child use the *env*
377 parameter rather than doing it in a *preexec_fn*.
378 The *start_new_session* parameter can take the place of a previously
379 common use of *preexec_fn* to call os.setsid() in the child.
Georg Brandl116aa622007-08-15 14:28:22 +0000380
381 If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and
382 :const:`2` will be closed before the child process is executed. (Unix only).
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000383 The default varies by platform: Always true on Unix. On Windows it is
384 true when *stdin*/*stdout*/*stderr* are :const:`None`, false otherwise.
Gregory P. Smithd23047b2010-12-04 09:10:44 +0000385 On Windows, if *close_fds* is true then no handles will be inherited by the
Georg Brandl116aa622007-08-15 14:28:22 +0000386 child process. Note that on Windows, you cannot set *close_fds* to true and
387 also redirect the standard handles by setting *stdin*, *stdout* or *stderr*.
388
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000389 .. versionchanged:: 3.2
390 The default for *close_fds* was changed from :const:`False` to
391 what is described above.
392
393 *pass_fds* is an optional sequence of file descriptors to keep open
394 between the parent and child. Providing any *pass_fds* forces
395 *close_fds* to be :const:`True`. (Unix only)
396
397 .. versionadded:: 3.2
398 The *pass_fds* parameter was added.
Georg Brandl116aa622007-08-15 14:28:22 +0000399
400 If *cwd* is not ``None``, the child's current directory will be changed to *cwd*
401 before it is executed. Note that this directory is not considered when
402 searching the executable, so you can't specify the program's path relative to
403 *cwd*.
404
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000405 If *restore_signals* is True (the default) all signals that Python has set to
406 SIG_IGN are restored to SIG_DFL in the child process before the exec.
407 Currently this includes the SIGPIPE, SIGXFZ and SIGXFSZ signals.
408 (Unix only)
409
410 .. versionchanged:: 3.2
411 *restore_signals* was added.
412
413 If *start_new_session* is True the setsid() system call will be made in the
414 child process prior to the execution of the subprocess. (Unix only)
415
416 .. versionchanged:: 3.2
417 *start_new_session* was added.
418
Christian Heimesa342c012008-04-20 21:01:16 +0000419 If *env* is not ``None``, it must be a mapping that defines the environment
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000420 variables for the new process; these are used instead of the default
421 behavior of inheriting the current process' environment.
Georg Brandl116aa622007-08-15 14:28:22 +0000422
R. David Murray1055e892009-04-16 18:15:32 +0000423 .. note::
R. David Murrayf4ac1492009-04-15 22:35:15 +0000424
Georg Brandl2708f3a2009-12-20 14:38:23 +0000425 If specified, *env* must provide any variables required for the program to
426 execute. On Windows, in order to run a `side-by-side assembly`_ the
427 specified *env* **must** include a valid :envvar:`SystemRoot`.
R. David Murrayf4ac1492009-04-15 22:35:15 +0000428
R. David Murray1055e892009-04-16 18:15:32 +0000429 .. _side-by-side assembly: http://en.wikipedia.org/wiki/Side-by-Side_Assembly
430
Georg Brandl116aa622007-08-15 14:28:22 +0000431 If *universal_newlines* is :const:`True`, the file objects stdout and stderr are
432 opened as text files, but lines may be terminated by any of ``'\n'``, the Unix
Georg Brandlc575c902008-09-13 17:46:05 +0000433 end-of-line convention, ``'\r'``, the old Macintosh convention or ``'\r\n'``, the
Georg Brandl116aa622007-08-15 14:28:22 +0000434 Windows convention. All of these external representations are seen as ``'\n'``
435 by the Python program.
436
437 .. note::
438
Georg Brandl7f01a132009-09-16 15:58:14 +0000439 This feature is only available if Python is built with universal newline
440 support (the default). Also, the newlines attribute of the file objects
441 :attr:`stdout`, :attr:`stdin` and :attr:`stderr` are not updated by the
442 :meth:`communicate` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000443
Brian Curtine6242d72011-04-29 22:17:51 -0500444 If given, *startupinfo* will be a :class:`STARTUPINFO` object, which is
445 passed to the underlying ``CreateProcess`` function.
Brian Curtin30401932011-04-29 22:20:57 -0500446 *creationflags*, if given, can be :data:`CREATE_NEW_CONSOLE` or
447 :data:`CREATE_NEW_PROCESS_GROUP`. (Windows only)
Georg Brandl116aa622007-08-15 14:28:22 +0000448
Gregory P. Smithc9557af2011-05-11 22:18:23 -0700449 Popen objects are supported as context managers via the :keyword:`with` statement:
450 on exit, standard file descriptors are closed, and the process is waited for.
Brian Curtin79cdb662010-12-03 02:46:02 +0000451 ::
452
453 with Popen(["ifconfig"], stdout=PIPE) as proc:
454 log.write(proc.stdout.read())
455
456 .. versionchanged:: 3.2
457 Added context manager support.
458
Georg Brandl116aa622007-08-15 14:28:22 +0000459
Georg Brandl116aa622007-08-15 14:28:22 +0000460Exceptions
461^^^^^^^^^^
462
463Exceptions raised in the child process, before the new program has started to
464execute, will be re-raised in the parent. Additionally, the exception object
465will have one extra attribute called :attr:`child_traceback`, which is a string
Georg Brandl81675612010-08-26 14:30:56 +0000466containing traceback information from the child's point of view.
Georg Brandl116aa622007-08-15 14:28:22 +0000467
468The most common exception raised is :exc:`OSError`. This occurs, for example,
469when trying to execute a non-existent file. Applications should prepare for
470:exc:`OSError` exceptions.
471
472A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid
473arguments.
474
Nick Coghlanc29248f2011-11-08 20:49:23 +1000475:func:`check_call` and :func:`check_output` will raise
476:exc:`CalledProcessError` if the called process returns a non-zero return
477code.
Georg Brandl116aa622007-08-15 14:28:22 +0000478
479
480Security
481^^^^^^^^
482
Nick Coghlanc29248f2011-11-08 20:49:23 +1000483Unlike some other popen functions, this implementation will never call a
484system shell implicitly. This means that all characters, including shell
485metacharacters, can safely be passed to child processes. Obviously, if the
486shell is invoked explicitly, then it is the application's responsibility to
487ensure that all whitespace and metacharacters are quoted appropriately.
Georg Brandl116aa622007-08-15 14:28:22 +0000488
489
490Popen Objects
491-------------
492
493Instances of the :class:`Popen` class have the following methods:
494
495
496.. method:: Popen.poll()
497
Christian Heimes7f044312008-01-06 17:05:40 +0000498 Check if child process has terminated. Set and return :attr:`returncode`
499 attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000500
501
502.. method:: Popen.wait()
503
Christian Heimes7f044312008-01-06 17:05:40 +0000504 Wait for child process to terminate. Set and return :attr:`returncode`
505 attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000506
Georg Brandl734e2682008-08-12 08:18:18 +0000507 .. warning::
508
Philip Jenveyb0896842009-12-03 02:29:36 +0000509 This will deadlock when using ``stdout=PIPE`` and/or
510 ``stderr=PIPE`` and the child process generates enough output to
511 a pipe such that it blocks waiting for the OS pipe buffer to
512 accept more data. Use :meth:`communicate` to avoid that.
Georg Brandl734e2682008-08-12 08:18:18 +0000513
Georg Brandl116aa622007-08-15 14:28:22 +0000514
515.. method:: Popen.communicate(input=None)
516
517 Interact with process: Send data to stdin. Read data from stdout and stderr,
518 until end-of-file is reached. Wait for process to terminate. The optional
Georg Brandle11787a2008-07-01 19:10:52 +0000519 *input* argument should be a byte string to be sent to the child process, or
Georg Brandl116aa622007-08-15 14:28:22 +0000520 ``None``, if no data should be sent to the child.
521
Georg Brandlaf265f42008-12-07 15:06:20 +0000522 :meth:`communicate` returns a tuple ``(stdoutdata, stderrdata)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000523
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000524 Note that if you want to send data to the process's stdin, you need to create
525 the Popen object with ``stdin=PIPE``. Similarly, to get anything other than
526 ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or
527 ``stderr=PIPE`` too.
528
Christian Heimes7f044312008-01-06 17:05:40 +0000529 .. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000530
Christian Heimes7f044312008-01-06 17:05:40 +0000531 The data read is buffered in memory, so do not use this method if the data
532 size is large or unlimited.
533
Georg Brandl116aa622007-08-15 14:28:22 +0000534
Christian Heimesa342c012008-04-20 21:01:16 +0000535.. method:: Popen.send_signal(signal)
536
537 Sends the signal *signal* to the child.
538
539 .. note::
540
Brian Curtineb24d742010-04-12 17:16:38 +0000541 On Windows, SIGTERM is an alias for :meth:`terminate`. CTRL_C_EVENT and
Senthil Kumaran916bd382010-10-15 12:55:19 +0000542 CTRL_BREAK_EVENT can be sent to processes started with a *creationflags*
Brian Curtineb24d742010-04-12 17:16:38 +0000543 parameter which includes `CREATE_NEW_PROCESS_GROUP`.
Christian Heimesa342c012008-04-20 21:01:16 +0000544
Christian Heimesa342c012008-04-20 21:01:16 +0000545
546.. method:: Popen.terminate()
547
548 Stop the child. On Posix OSs the method sends SIGTERM to the
Georg Brandl60203b42010-10-06 10:11:56 +0000549 child. On Windows the Win32 API function :c:func:`TerminateProcess` is called
Christian Heimesa342c012008-04-20 21:01:16 +0000550 to stop the child.
551
Christian Heimesa342c012008-04-20 21:01:16 +0000552
553.. method:: Popen.kill()
554
555 Kills the child. On Posix OSs the function sends SIGKILL to the child.
556 On Windows :meth:`kill` is an alias for :meth:`terminate`.
557
Christian Heimesa342c012008-04-20 21:01:16 +0000558
Georg Brandl116aa622007-08-15 14:28:22 +0000559The following attributes are also available:
560
Georg Brandl734e2682008-08-12 08:18:18 +0000561.. warning::
562
Georg Brandle720c0a2009-04-27 16:20:50 +0000563 Use :meth:`communicate` rather than :attr:`.stdin.write <stdin>`,
564 :attr:`.stdout.read <stdout>` or :attr:`.stderr.read <stderr>` to avoid
565 deadlocks due to any of the other OS pipe buffers filling up and blocking the
566 child process.
Georg Brandl734e2682008-08-12 08:18:18 +0000567
568
Georg Brandl116aa622007-08-15 14:28:22 +0000569.. attribute:: Popen.stdin
570
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000571 If the *stdin* argument was :data:`PIPE`, this attribute is a :term:`file
572 object` that provides input to the child process. Otherwise, it is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000573
574
575.. attribute:: Popen.stdout
576
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000577 If the *stdout* argument was :data:`PIPE`, this attribute is a :term:`file
578 object` that provides output from the child process. Otherwise, it is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000579
580
581.. attribute:: Popen.stderr
582
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000583 If the *stderr* argument was :data:`PIPE`, this attribute is a :term:`file
584 object` that provides error output from the child process. Otherwise, it is
Georg Brandlaf265f42008-12-07 15:06:20 +0000585 ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000586
587
588.. attribute:: Popen.pid
589
590 The process ID of the child process.
591
Georg Brandl58bfdca2010-03-21 09:50:49 +0000592 Note that if you set the *shell* argument to ``True``, this is the process ID
593 of the spawned shell.
594
Georg Brandl116aa622007-08-15 14:28:22 +0000595
596.. attribute:: Popen.returncode
597
Christian Heimes7f044312008-01-06 17:05:40 +0000598 The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly
599 by :meth:`communicate`). A ``None`` value indicates that the process
600 hasn't terminated yet.
Georg Brandl48310cd2009-01-03 21:18:54 +0000601
Christian Heimes7f044312008-01-06 17:05:40 +0000602 A negative value ``-N`` indicates that the child was terminated by signal
603 ``N`` (Unix only).
Georg Brandl116aa622007-08-15 14:28:22 +0000604
605
Brian Curtine6242d72011-04-29 22:17:51 -0500606Windows Popen Helpers
607---------------------
608
609The :class:`STARTUPINFO` class and following constants are only available
610on Windows.
611
612.. class:: STARTUPINFO()
Brian Curtin73365dd2011-04-29 22:18:33 -0500613
Brian Curtine6242d72011-04-29 22:17:51 -0500614 Partial support of the Windows
615 `STARTUPINFO <http://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx>`__
616 structure is used for :class:`Popen` creation.
617
618 .. attribute:: dwFlags
619
Senthil Kumarana6bac952011-07-04 11:28:30 -0700620 A bit field that determines whether certain :class:`STARTUPINFO`
621 attributes are used when the process creates a window. ::
Brian Curtine6242d72011-04-29 22:17:51 -0500622
623 si = subprocess.STARTUPINFO()
624 si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
625
626 .. attribute:: hStdInput
627
Senthil Kumarana6bac952011-07-04 11:28:30 -0700628 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
629 is the standard input handle for the process. If
630 :data:`STARTF_USESTDHANDLES` is not specified, the default for standard
631 input is the keyboard buffer.
Brian Curtine6242d72011-04-29 22:17:51 -0500632
633 .. attribute:: hStdOutput
634
Senthil Kumarana6bac952011-07-04 11:28:30 -0700635 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
636 is the standard output handle for the process. Otherwise, this attribute
637 is ignored and the default for standard output is the console window's
Brian Curtine6242d72011-04-29 22:17:51 -0500638 buffer.
639
640 .. attribute:: hStdError
641
Senthil Kumarana6bac952011-07-04 11:28:30 -0700642 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
643 is the standard error handle for the process. Otherwise, this attribute is
Brian Curtine6242d72011-04-29 22:17:51 -0500644 ignored and the default for standard error is the console window's buffer.
645
646 .. attribute:: wShowWindow
647
Senthil Kumarana6bac952011-07-04 11:28:30 -0700648 If :attr:`dwFlags` specifies :data:`STARTF_USESHOWWINDOW`, this attribute
Brian Curtine6242d72011-04-29 22:17:51 -0500649 can be any of the values that can be specified in the ``nCmdShow``
650 parameter for the
651 `ShowWindow <http://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx>`__
Senthil Kumarana6bac952011-07-04 11:28:30 -0700652 function, except for ``SW_SHOWDEFAULT``. Otherwise, this attribute is
Brian Curtine6242d72011-04-29 22:17:51 -0500653 ignored.
Brian Curtin73365dd2011-04-29 22:18:33 -0500654
Brian Curtine6242d72011-04-29 22:17:51 -0500655 :data:`SW_HIDE` is provided for this attribute. It is used when
656 :class:`Popen` is called with ``shell=True``.
657
658
659Constants
660^^^^^^^^^
661
662The :mod:`subprocess` module exposes the following constants.
663
664.. data:: STD_INPUT_HANDLE
665
666 The standard input device. Initially, this is the console input buffer,
667 ``CONIN$``.
668
669.. data:: STD_OUTPUT_HANDLE
670
671 The standard output device. Initially, this is the active console screen
672 buffer, ``CONOUT$``.
673
674.. data:: STD_ERROR_HANDLE
675
676 The standard error device. Initially, this is the active console screen
677 buffer, ``CONOUT$``.
678
679.. data:: SW_HIDE
680
681 Hides the window. Another window will be activated.
682
683.. data:: STARTF_USESTDHANDLES
684
685 Specifies that the :attr:`STARTUPINFO.hStdInput`,
Senthil Kumarana6bac952011-07-04 11:28:30 -0700686 :attr:`STARTUPINFO.hStdOutput`, and :attr:`STARTUPINFO.hStdError` attributes
Brian Curtine6242d72011-04-29 22:17:51 -0500687 contain additional information.
688
689.. data:: STARTF_USESHOWWINDOW
690
Senthil Kumarana6bac952011-07-04 11:28:30 -0700691 Specifies that the :attr:`STARTUPINFO.wShowWindow` attribute contains
Brian Curtine6242d72011-04-29 22:17:51 -0500692 additional information.
693
694.. data:: CREATE_NEW_CONSOLE
695
696 The new process has a new console, instead of inheriting its parent's
697 console (the default).
Brian Curtin73365dd2011-04-29 22:18:33 -0500698
Brian Curtine6242d72011-04-29 22:17:51 -0500699 This flag is always set when :class:`Popen` is created with ``shell=True``.
700
Brian Curtin30401932011-04-29 22:20:57 -0500701.. data:: CREATE_NEW_PROCESS_GROUP
702
703 A :class:`Popen` ``creationflags`` parameter to specify that a new process
704 group will be created. This flag is necessary for using :func:`os.kill`
705 on the subprocess.
706
707 This flag is ignored if :data:`CREATE_NEW_CONSOLE` is specified.
708
Brian Curtine6242d72011-04-29 22:17:51 -0500709
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000710.. _subprocess-replacements:
711
Georg Brandl116aa622007-08-15 14:28:22 +0000712Replacing Older Functions with the subprocess Module
713----------------------------------------------------
714
Nick Coghlanc29248f2011-11-08 20:49:23 +1000715In this section, "a becomes b" means that b can be used as a replacement for a.
Georg Brandl116aa622007-08-15 14:28:22 +0000716
717.. note::
718
Nick Coghlanc29248f2011-11-08 20:49:23 +1000719 All "a" functions in this section fail (more or less) silently if the
720 executed program cannot be found; the "b" replacements raise :exc:`OSError`
721 instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000722
Nick Coghlanc29248f2011-11-08 20:49:23 +1000723 In addition, the replacements using :func:`check_output` will fail with a
724 :exc:`CalledProcessError` if the requested operation produces a non-zero
725 return code. The output is still available as the ``output`` attribute of
726 the raised exception.
727
728In the following examples, we assume that the relevant functions have already
729been imported from the subprocess module.
Georg Brandl116aa622007-08-15 14:28:22 +0000730
731
732Replacing /bin/sh shell backquote
733^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
734
735::
736
737 output=`mycmd myarg`
Nick Coghlanc29248f2011-11-08 20:49:23 +1000738 # becomes
739 output = check_output(["mycmd", "myarg"])
Georg Brandl116aa622007-08-15 14:28:22 +0000740
741
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000742Replacing shell pipeline
743^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000744
745::
746
747 output=`dmesg | grep hda`
Nick Coghlanc29248f2011-11-08 20:49:23 +1000748 # becomes
Georg Brandl116aa622007-08-15 14:28:22 +0000749 p1 = Popen(["dmesg"], stdout=PIPE)
750 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Gregory P. Smithe09d2f12011-02-05 21:47:25 +0000751 p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
Georg Brandl116aa622007-08-15 14:28:22 +0000752 output = p2.communicate()[0]
753
Gregory P. Smithe09d2f12011-02-05 21:47:25 +0000754The p1.stdout.close() call after starting the p2 is important in order for p1
755to receive a SIGPIPE if p2 exits before p1.
Georg Brandl116aa622007-08-15 14:28:22 +0000756
Nick Coghlanc29248f2011-11-08 20:49:23 +1000757Alternatively, for trusted input, the shell's own pipeline support may still
R David Murray28b8b942012-04-03 08:46:48 -0400758be used directly::
Nick Coghlanc29248f2011-11-08 20:49:23 +1000759
760 output=`dmesg | grep hda`
761 # becomes
762 output=check_output("dmesg | grep hda", shell=True)
763
764
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000765Replacing :func:`os.system`
766^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000767
768::
769
770 sts = os.system("mycmd" + " myarg")
Nick Coghlanc29248f2011-11-08 20:49:23 +1000771 # becomes
772 sts = call("mycmd" + " myarg", shell=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000773
774Notes:
775
776* Calling the program through the shell is usually not required.
777
Georg Brandl116aa622007-08-15 14:28:22 +0000778A more realistic example would look like this::
779
780 try:
781 retcode = call("mycmd" + " myarg", shell=True)
782 if retcode < 0:
Collin Winterc79461b2007-09-01 23:34:30 +0000783 print("Child was terminated by signal", -retcode, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000784 else:
Collin Winterc79461b2007-09-01 23:34:30 +0000785 print("Child returned", retcode, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000786 except OSError as e:
Collin Winterc79461b2007-09-01 23:34:30 +0000787 print("Execution failed:", e, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000788
789
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000790Replacing the :func:`os.spawn <os.spawnl>` family
791^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000792
793P_NOWAIT example::
794
795 pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
796 ==>
797 pid = Popen(["/bin/mycmd", "myarg"]).pid
798
799P_WAIT example::
800
801 retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
802 ==>
803 retcode = call(["/bin/mycmd", "myarg"])
804
805Vector example::
806
807 os.spawnvp(os.P_NOWAIT, path, args)
808 ==>
809 Popen([path] + args[1:])
810
811Environment example::
812
813 os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
814 ==>
815 Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
816
817
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000818
819Replacing :func:`os.popen`, :func:`os.popen2`, :func:`os.popen3`
820^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000821
822::
823
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000824 (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
Georg Brandl116aa622007-08-15 14:28:22 +0000825 ==>
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000826 p = Popen(cmd, shell=True, bufsize=bufsize,
827 stdin=PIPE, stdout=PIPE, close_fds=True)
828 (child_stdin, child_stdout) = (p.stdin, p.stdout)
Georg Brandl116aa622007-08-15 14:28:22 +0000829
830::
831
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000832 (child_stdin,
833 child_stdout,
834 child_stderr) = os.popen3(cmd, mode, bufsize)
Georg Brandl116aa622007-08-15 14:28:22 +0000835 ==>
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000836 p = Popen(cmd, shell=True, bufsize=bufsize,
837 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
838 (child_stdin,
839 child_stdout,
840 child_stderr) = (p.stdin, p.stdout, p.stderr)
841
842::
843
844 (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
845 ==>
846 p = Popen(cmd, shell=True, bufsize=bufsize,
847 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
848 (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
849
850Return code handling translates as follows::
851
852 pipe = os.popen(cmd, 'w')
853 ...
854 rc = pipe.close()
Stefan Krahfc9e08d2010-07-14 10:16:11 +0000855 if rc is not None and rc >> 8:
Ezio Melotti985e24d2009-09-13 07:54:02 +0000856 print("There were some errors")
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000857 ==>
858 process = Popen(cmd, 'w', stdin=PIPE)
859 ...
860 process.stdin.close()
861 if process.wait() != 0:
Ezio Melotti985e24d2009-09-13 07:54:02 +0000862 print("There were some errors")
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000863
864
865Replacing functions from the :mod:`popen2` module
866^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
867
868.. note::
869
870 If the cmd argument to popen2 functions is a string, the command is executed
871 through /bin/sh. If it is a list, the command is directly executed.
872
873::
874
875 (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
876 ==>
877 p = Popen(["somestring"], shell=True, bufsize=bufsize,
878 stdin=PIPE, stdout=PIPE, close_fds=True)
879 (child_stdout, child_stdin) = (p.stdout, p.stdin)
880
881::
882
883 (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
884 ==>
885 p = Popen(["mycmd", "myarg"], bufsize=bufsize,
886 stdin=PIPE, stdout=PIPE, close_fds=True)
887 (child_stdout, child_stdin) = (p.stdout, p.stdin)
888
889:class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as
890:class:`subprocess.Popen`, except that:
891
892* :class:`Popen` raises an exception if the execution fails.
893
894* the *capturestderr* argument is replaced with the *stderr* argument.
895
896* ``stdin=PIPE`` and ``stdout=PIPE`` must be specified.
897
898* popen2 closes all file descriptors by default, but you have to specify
Gregory P. Smithf5604852010-12-13 06:45:02 +0000899 ``close_fds=True`` with :class:`Popen` to guarantee this behavior on
900 all platforms or past Python versions.
Eli Bendersky046a7642011-04-15 07:23:26 +0300901
Nick Coghlanc29248f2011-11-08 20:49:23 +1000902
Nick Coghlanc29248f2011-11-08 20:49:23 +1000903Legacy Shell Invocation Functions
Nick Coghlan32e4a582011-11-08 21:50:58 +1000904---------------------------------
Nick Coghlanc29248f2011-11-08 20:49:23 +1000905
906This module also provides the following legacy functions from the 2.x
907``commands`` module. These operations implicitly invoke the system shell and
908none of the guarantees described above regarding security and exception
909handling consistency are valid for these functions.
910
911.. function:: getstatusoutput(cmd)
912
913 Return ``(status, output)`` of executing *cmd* in a shell.
914
915 Execute the string *cmd* in a shell with :func:`os.popen` and return a 2-tuple
916 ``(status, output)``. *cmd* is actually run as ``{ cmd ; } 2>&1``, so that the
917 returned output will contain output or error messages. A trailing newline is
918 stripped from the output. The exit status for the command can be interpreted
919 according to the rules for the C function :c:func:`wait`. Example::
920
921 >>> subprocess.getstatusoutput('ls /bin/ls')
922 (0, '/bin/ls')
923 >>> subprocess.getstatusoutput('cat /bin/junk')
924 (256, 'cat: /bin/junk: No such file or directory')
925 >>> subprocess.getstatusoutput('/bin/junk')
926 (256, 'sh: /bin/junk: not found')
927
928 Availability: UNIX.
929
930
931.. function:: getoutput(cmd)
932
933 Return output (stdout and stderr) of executing *cmd* in a shell.
934
935 Like :func:`getstatusoutput`, except the exit status is ignored and the return
936 value is a string containing the command's output. Example::
937
938 >>> subprocess.getoutput('ls /bin/ls')
939 '/bin/ls'
940
941 Availability: UNIX.
942
Nick Coghlan32e4a582011-11-08 21:50:58 +1000943
944Notes
945-----
946
947.. _converting-argument-sequence:
948
949Converting an argument sequence to a string on Windows
950^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
951
952On Windows, an *args* sequence is converted to a string that can be parsed
953using the following rules (which correspond to the rules used by the MS C
954runtime):
955
9561. Arguments are delimited by white space, which is either a
957 space or a tab.
958
9592. A string surrounded by double quotation marks is
960 interpreted as a single argument, regardless of white space
961 contained within. A quoted string can be embedded in an
962 argument.
963
9643. A double quotation mark preceded by a backslash is
965 interpreted as a literal double quotation mark.
966
9674. Backslashes are interpreted literally, unless they
968 immediately precede a double quotation mark.
969
9705. If backslashes immediately precede a double quotation mark,
971 every pair of backslashes is interpreted as a literal
972 backslash. If the number of backslashes is odd, the last
973 backslash escapes the next double quotation mark as
974 described in rule 3.