blob: ee46d728412f0e5899b64c059cc19612a2fd83cd [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2:mod:`subprocess` --- Subprocess management
3===========================================
4
5.. module:: subprocess
6 :synopsis: Subprocess management.
7.. moduleauthor:: Peter Åstrand <astrand@lysator.liu.se>
8.. sectionauthor:: Peter Åstrand <astrand@lysator.liu.se>
9
10
11.. versionadded:: 2.4
12
13The :mod:`subprocess` module allows you to spawn new processes, connect to their
14input/output/error pipes, and obtain their return codes. This module intends to
15replace several other, older modules and functions, such as::
16
17 os.system
18 os.spawn*
19 os.popen*
20 popen2.*
21 commands.*
22
23Information about how the :mod:`subprocess` module can be used to replace these
24modules and functions can be found in the following sections.
25
Georg Brandl68b4e742008-07-01 19:59:00 +000026.. seealso::
27
28 :pep:`324` -- PEP proposing the subprocess module
29
Georg Brandl8ec7f652007-08-15 14:28:01 +000030
31Using the subprocess Module
32---------------------------
33
Nick Coghlan2ed203a2011-10-26 21:05:56 +100034The recommended approach to invoking subprocesses is to use the following
35convenience functions for all use cases they can handle. For more advanced
36use cases, the underlying :class:`Popen` interface can be used directly.
Nick Coghlan86711572011-10-24 22:19:40 +100037
38
Nick Coghlan2ed203a2011-10-26 21:05:56 +100039.. function:: call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
Nick Coghlan86711572011-10-24 22:19:40 +100040
41 Run the command described by *args*. Wait for command to complete, then
42 return the :attr:`returncode` attribute.
43
44 The arguments shown above are merely the most common ones, described below
45 in :ref:`frequently-used-arguments`. The full function signature is the
46 same as that of the :class:`Popen` constructor - the convenience functions
47 pass all supplied arguments directly through to that interface.
48
49 Examples::
50
51 >>> subprocess.call(["ls", "-l"])
52 0
53
Nick Coghlan2ed203a2011-10-26 21:05:56 +100054 >>> subprocess.call("exit 1", shell=True)
Nick Coghlan86711572011-10-24 22:19:40 +100055 1
56
57 .. warning::
58
Nick Coghlan2ed203a2011-10-26 21:05:56 +100059 Do not use ``stdout=PIPE`` or ``stderr=PIPE`` with this function. As
60 the pipes are not being read in the current process, the child
61 process may block if it generates enough output to a pipe to fill up
62 the OS pipe buffer.
Nick Coghlan86711572011-10-24 22:19:40 +100063
64
65.. function:: check_call(*callargs, **kwargs)
66
67 Run command with arguments. Wait for command to complete. If the return
68 code was zero then return, otherwise raise :exc:`CalledProcessError`. The
69 :exc:`CalledProcessError` object will have the return code in the
70 :attr:`returncode` attribute.
71
72 The arguments are the same as for :func:`call`. Examples::
73
74 >>> subprocess.check_call(["ls", "-l"])
75 0
76
Nick Coghlan2ed203a2011-10-26 21:05:56 +100077 >>> subprocess.check_call("exit 1", shell=True)
Nick Coghlan86711572011-10-24 22:19:40 +100078 Traceback (most recent call last):
79 ...
Nick Coghlan2ed203a2011-10-26 21:05:56 +100080 subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
Nick Coghlan86711572011-10-24 22:19:40 +100081
82 .. versionadded:: 2.5
83
84 .. warning::
85
86 See the warning for :func:`call`.
87
88
89.. function:: check_output(*callargs, **kwargs)
90
91 Run command with arguments and return its output as a byte string.
92
93 If the return code was non-zero it raises a :exc:`CalledProcessError`. The
94 :exc:`CalledProcessError` object will have the return code in the
95 :attr:`returncode` attribute and any output in the :attr:`output`
96 attribute.
97
Nick Coghlan2ed203a2011-10-26 21:05:56 +100098 The arguments are the same as for :func:`call`, except that *stdout* is
99 not permitted as it is used internally.
100
Nick Coghlan86711572011-10-24 22:19:40 +1000101 Examples::
102
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000103 >>> subprocess.check_output(["echo", "Hello World!"])
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000104 'Hello World!\n'
105
106 >>> subprocess.check_output("exit 1", shell=True)
Nick Coghlan86711572011-10-24 22:19:40 +1000107 Traceback (most recent call last):
108 ...
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000109 subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
Nick Coghlan86711572011-10-24 22:19:40 +1000110
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000111 To also capture standard error in the result, use
112 ``stderr=subprocess.STDOUT``::
Nick Coghlan86711572011-10-24 22:19:40 +1000113
114 >>> subprocess.check_output(
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000115 ... "ls non_existent_file; exit 0",
116 ... stderr=subprocess.STDOUT,
117 ... shell=True)
Nick Coghlan86711572011-10-24 22:19:40 +1000118 'ls: non_existent_file: No such file or directory\n'
119
120 .. versionadded:: 2.7
121
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000122 .. warning::
123
124 Do not use ``stderr=PIPE`` with this function. As the pipe is not being
125 read in the current process, the child process may block if it
126 generates enough output to the pipe to fill up the OS pipe buffer.
127
Nick Coghlan86711572011-10-24 22:19:40 +1000128
129.. data:: PIPE
130
131 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
132 to :class:`Popen` and indicates that a pipe to the standard stream should be
133 opened.
134
135
136.. data:: STDOUT
137
138 Special value that can be used as the *stderr* argument to :class:`Popen` and
139 indicates that standard error should go into the same handle as standard
140 output.
141
142
143.. _frequently-used-arguments:
144
145Frequently Used Arguments
146^^^^^^^^^^^^^^^^^^^^^^^^^
147
148To support a wide variety of use cases, the :class:`Popen` constructor (and
149the convenience functions) accept a large number of optional arguments. For
150most typical use cases, many of these arguments can be safely left at their
151default values. The arguments that are most commonly needed are:
152
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000153 *args* is required for all calls and should be a string, or a sequence of
154 program arguments. Providing a sequence of arguments is generally
155 preferred, as it allows the module to take care of any required escaping
156 and quoting of arguments (e.g. to permit spaces in file names). If passing
157 a single string, either *shell* must be :const:`True` (see below) or else
158 the string must simply name the program to be executed without specifying
159 any arguments.
Nick Coghlan86711572011-10-24 22:19:40 +1000160
161 *stdin*, *stdout* and *stderr* specify the executed program's standard input,
162 standard output and standard error file handles, respectively. Valid values
163 are :data:`PIPE`, an existing file descriptor (a positive integer), an
164 existing file object, and ``None``. :data:`PIPE` indicates that a new pipe
165 to the child should be created. With the default settings of ``None``, no
166 redirection will occur; the child's file handles will be inherited from the
167 parent. Additionally, *stderr* can be :data:`STDOUT`, which indicates that
168 the stderr data from the child process should be captured into the same file
169 handle as for stdout.
170
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000171 When *stdout* or *stderr* are pipes and *universal_newlines* is
Nick Coghlan65ad31a2011-10-26 21:15:53 +1000172 :const:`True` then all line endings will be converted to ``'\n'`` as
173 described for the universal newlines `'U'`` mode argument to :func:`open`.
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000174
175 If *shell* is :const:`True`, the specified command will be executed through
176 the shell. This can be useful if you are using Python primarily for the
177 enhanced control flow it offers over most system shells and still want
178 access to other shell features such as filename wildcards, shell pipes and
179 environment variable expansion.
180
181 .. warning::
182
183 Executing shell commands that incorporate unsanitized input from an
184 untrusted source makes a program vulnerable to `shell injection
185 <http://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_,
186 a serious security flaw which can result in arbitrary command execution.
187 For this reason, the use of *shell=True* is **strongly discouraged** in cases
188 where the command string is constructed from external input::
189
190 >>> from subprocess import call
191 >>> filename = input("What file would you like to display?\n")
192 What file would you like to display?
193 non_existent; rm -rf / #
194 >>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...
195
196 ``shell=False`` disables all shell based features, but does not suffer
197 from this vulnerability; see the Note in the :class:`Popen` constructor
198 documentation for helpful hints in getting ``shell=False`` to work.
199
Nick Coghlan86711572011-10-24 22:19:40 +1000200These options, along with all of the other options, are described in more
201detail in the :class:`Popen` constructor documentation.
202
203
204Popen Constuctor
205^^^^^^^^^^^^^^^^
206
207The underlying process creation and management in this module is handled by
208the :class:`Popen` class. It offers a lot of flexibility so that developers
209are able to handle the less common cases not covered by the convenience
210functions.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000211
212
213.. class:: Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)
214
215 Arguments are:
216
Benjamin Petersonfff5cf62008-07-27 15:22:14 +0000217 *args* should be a string, or a sequence of program arguments. The program
R. David Murrayfe6e7842009-05-29 19:30:27 +0000218 to execute is normally the first item in the args sequence or the string if
219 a string is given, but can be explicitly set by using the *executable*
220 argument. When *executable* is given, the first item in the args sequence
221 is still treated by most programs as the command name, which can then be
222 different from the actual executable name. On Unix, it becomes the display
223 name for the executing program in utilities such as :program:`ps`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000224
225 On Unix, with *shell=False* (default): In this case, the Popen class uses
226 :meth:`os.execvp` to execute the child program. *args* should normally be a
Nick Coghlan7dfc9e12010-02-04 12:43:58 +0000227 sequence. If a string is specified for *args*, it will be used as the name
228 or path of the program to execute; this will only work if the program is
229 being given no arguments.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000230
Nick Coghlan7dfc9e12010-02-04 12:43:58 +0000231 .. note::
232
233 :meth:`shlex.split` can be useful when determining the correct
234 tokenization for *args*, especially in complex cases::
235
236 >>> import shlex, subprocess
237 >>> command_line = raw_input()
238 /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
239 >>> args = shlex.split(command_line)
240 >>> print args
241 ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
242 >>> p = subprocess.Popen(args) # Success!
243
244 Note in particular that options (such as *-input*) and arguments (such
245 as *eggs.txt*) that are separated by whitespace in the shell go in separate
246 list elements, while arguments that need quoting or backslash escaping when
247 used in the shell (such as filenames containing spaces or the *echo* command
248 shown above) are single list elements.
249
250 On Unix, with *shell=True*: If args is a string, it specifies the command
251 string to execute through the shell. This means that the string must be
252 formatted exactly as it would be when typed at the shell prompt. This
253 includes, for example, quoting or backslash escaping filenames with spaces in
254 them. If *args* is a sequence, the first item specifies the command string, and
255 any additional items will be treated as additional arguments to the shell
256 itself. That is to say, *Popen* does the equivalent of::
257
258 Popen(['/bin/sh', '-c', args[0], args[1], ...])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000259
260 On Windows: the :class:`Popen` class uses CreateProcess() to execute the child
Eli Bendersky929e2762011-04-15 07:35:06 +0300261 child program, which operates on strings. If *args* is a sequence, it will
262 be converted to a string in a manner described in
263 :ref:`converting-argument-sequence`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000264
265 *bufsize*, if given, has the same meaning as the corresponding argument to the
266 built-in open() function: :const:`0` means unbuffered, :const:`1` means line
267 buffered, any other positive value means use a buffer of (approximately) that
268 size. A negative *bufsize* means to use the system default, which usually means
269 fully buffered. The default value for *bufsize* is :const:`0` (unbuffered).
270
Antoine Pitrouc3955452010-06-02 17:08:47 +0000271 .. note::
272
273 If you experience performance issues, it is recommended that you try to
274 enable buffering by setting *bufsize* to either -1 or a large enough
275 positive value (such as 4096).
276
Georg Brandl8ec7f652007-08-15 14:28:01 +0000277 The *executable* argument specifies the program to execute. It is very seldom
278 needed: Usually, the program to execute is defined by the *args* argument. If
279 ``shell=True``, the *executable* argument specifies which shell to use. On Unix,
280 the default shell is :file:`/bin/sh`. On Windows, the default shell is
Georg Brandl0d8649a2009-06-30 16:17:28 +0000281 specified by the :envvar:`COMSPEC` environment variable. The only reason you
282 would need to specify ``shell=True`` on Windows is where the command you
283 wish to execute is actually built in to the shell, eg ``dir``, ``copy``.
284 You don't need ``shell=True`` to run a batch file, nor to run a console-based
285 executable.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000286
Nick Coghlan86711572011-10-24 22:19:40 +1000287 *stdin*, *stdout* and *stderr* specify the executed program's standard input,
Georg Brandlf5d5a662008-12-06 11:57:12 +0000288 standard output and standard error file handles, respectively. Valid values
289 are :data:`PIPE`, an existing file descriptor (a positive integer), an
290 existing file object, and ``None``. :data:`PIPE` indicates that a new pipe
Nick Coghlan86711572011-10-24 22:19:40 +1000291 to the child should be created. With the default settings of ``None``, no
292 redirection will occur; the child's file handles will be inherited from the
293 parent. Additionally, *stderr* can be :data:`STDOUT`, which indicates that
294 the stderr data from the child process should be captured into the same file
295 handle as for stdout.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000296
297 If *preexec_fn* is set to a callable object, this object will be called in the
298 child process just before the child is executed. (Unix only)
299
300 If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and
301 :const:`2` will be closed before the child process is executed. (Unix only).
302 Or, on Windows, if *close_fds* is true then no handles will be inherited by the
303 child process. Note that on Windows, you cannot set *close_fds* to true and
304 also redirect the standard handles by setting *stdin*, *stdout* or *stderr*.
305
306 If *shell* is :const:`True`, the specified command will be executed through the
307 shell.
308
Nick Coghlan65ad31a2011-10-26 21:15:53 +1000309 .. note::
310
311 Enabling this option can be a security hazard if combined with untrusted
312 input. See the warning under :ref:`frequently-used-arguments`
313 for details.
314
Georg Brandl8ec7f652007-08-15 14:28:01 +0000315 If *cwd* is not ``None``, the child's current directory will be changed to *cwd*
316 before it is executed. Note that this directory is not considered when
317 searching the executable, so you can't specify the program's path relative to
318 *cwd*.
319
Georg Brandlf801b0f2008-04-19 16:58:49 +0000320 If *env* is not ``None``, it must be a mapping that defines the environment
321 variables for the new process; these are used instead of inheriting the current
322 process' environment, which is the default behavior.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000323
R. David Murray72030812009-04-16 18:12:53 +0000324 .. note::
R. David Murray6076d392009-04-15 22:33:07 +0000325
R. David Murray72030812009-04-16 18:12:53 +0000326 If specified, *env* must provide any variables required
327 for the program to execute. On Windows, in order to run a
328 `side-by-side assembly`_ the specified *env* **must** include a valid
R. David Murray6076d392009-04-15 22:33:07 +0000329 :envvar:`SystemRoot`.
330
R. David Murray72030812009-04-16 18:12:53 +0000331 .. _side-by-side assembly: http://en.wikipedia.org/wiki/Side-by-Side_Assembly
332
Georg Brandl8ec7f652007-08-15 14:28:01 +0000333 If *universal_newlines* is :const:`True`, the file objects stdout and stderr are
334 opened as text files, but lines may be terminated by any of ``'\n'``, the Unix
Georg Brandl9af94982008-09-13 17:41:16 +0000335 end-of-line convention, ``'\r'``, the old Macintosh convention or ``'\r\n'``, the
Georg Brandl8ec7f652007-08-15 14:28:01 +0000336 Windows convention. All of these external representations are seen as ``'\n'``
337 by the Python program.
338
339 .. note::
340
Georg Brandl6ab5d082009-12-20 14:33:20 +0000341 This feature is only available if Python is built with universal newline
342 support (the default). Also, the newlines attribute of the file objects
343 :attr:`stdout`, :attr:`stdin` and :attr:`stderr` are not updated by the
344 communicate() method.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000345
Brian Curtinbb23bd62011-04-29 22:23:46 -0500346 If given, *startupinfo* will be a :class:`STARTUPINFO` object, which is
347 passed to the underlying ``CreateProcess`` function.
348 *creationflags*, if given, can be :data:`CREATE_NEW_CONSOLE` or
349 :data:`CREATE_NEW_PROCESS_GROUP`. (Windows only)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000350
351
Georg Brandl8ec7f652007-08-15 14:28:01 +0000352Exceptions
353^^^^^^^^^^
354
355Exceptions raised in the child process, before the new program has started to
356execute, will be re-raised in the parent. Additionally, the exception object
357will have one extra attribute called :attr:`child_traceback`, which is a string
Georg Brandl21946af2010-10-06 09:28:45 +0000358containing traceback information from the child's point of view.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000359
360The most common exception raised is :exc:`OSError`. This occurs, for example,
361when trying to execute a non-existent file. Applications should prepare for
362:exc:`OSError` exceptions.
363
364A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid
365arguments.
366
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000367:func:`check_call` and :func:`check_output` will raise
368:exc:`CalledProcessError` if the called process returns a non-zero return
369code.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000370
371
372Security
373^^^^^^^^
374
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000375Unlike some other popen functions, this implementation will never call a
376system shell implicitly. This means that all characters, including shell
377metacharacters, can safely be passed to child processes. Obviously, if the
378shell is invoked explicitly, then it is the application's responsibility to
Nick Coghlan63c54e82011-10-26 21:34:26 +1000379ensure that all whitespace and metacharacters are quoted appropriately.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000380
381
382Popen Objects
383-------------
384
385Instances of the :class:`Popen` class have the following methods:
386
387
388.. method:: Popen.poll()
389
Georg Brandl2cb103f2008-01-06 16:01:26 +0000390 Check if child process has terminated. Set and return :attr:`returncode`
391 attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000392
393
394.. method:: Popen.wait()
395
Georg Brandl2cb103f2008-01-06 16:01:26 +0000396 Wait for child process to terminate. Set and return :attr:`returncode`
397 attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000398
Georg Brandl143de622008-08-04 06:29:36 +0000399 .. warning::
400
Philip Jenvey26275532009-12-03 02:25:54 +0000401 This will deadlock when using ``stdout=PIPE`` and/or
402 ``stderr=PIPE`` and the child process generates enough output to
403 a pipe such that it blocks waiting for the OS pipe buffer to
404 accept more data. Use :meth:`communicate` to avoid that.
Gregory P. Smith08792502008-08-04 01:03:50 +0000405
Georg Brandl8ec7f652007-08-15 14:28:01 +0000406
407.. method:: Popen.communicate(input=None)
408
409 Interact with process: Send data to stdin. Read data from stdout and stderr,
410 until end-of-file is reached. Wait for process to terminate. The optional
411 *input* argument should be a string to be sent to the child process, or
412 ``None``, if no data should be sent to the child.
413
Georg Brandl17432012008-12-04 21:28:16 +0000414 :meth:`communicate` returns a tuple ``(stdoutdata, stderrdata)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000415
Georg Brandl439f2502007-11-24 11:31:46 +0000416 Note that if you want to send data to the process's stdin, you need to create
417 the Popen object with ``stdin=PIPE``. Similarly, to get anything other than
418 ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or
419 ``stderr=PIPE`` too.
420
Georg Brandl2cb103f2008-01-06 16:01:26 +0000421 .. note::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000422
Georg Brandl2cb103f2008-01-06 16:01:26 +0000423 The data read is buffered in memory, so do not use this method if the data
424 size is large or unlimited.
425
Georg Brandl8ec7f652007-08-15 14:28:01 +0000426
Christian Heimese74c8f22008-04-19 02:23:57 +0000427.. method:: Popen.send_signal(signal)
428
429 Sends the signal *signal* to the child.
430
431 .. note::
432
Brian Curtine5aa8862010-04-02 23:26:06 +0000433 On Windows, SIGTERM is an alias for :meth:`terminate`. CTRL_C_EVENT and
Ezio Melotti9ccc5812010-04-05 08:16:41 +0000434 CTRL_BREAK_EVENT can be sent to processes started with a *creationflags*
Brian Curtine5aa8862010-04-02 23:26:06 +0000435 parameter which includes `CREATE_NEW_PROCESS_GROUP`.
Georg Brandl734de682008-04-19 08:23:59 +0000436
437 .. versionadded:: 2.6
Christian Heimese74c8f22008-04-19 02:23:57 +0000438
439
440.. method:: Popen.terminate()
441
442 Stop the child. On Posix OSs the method sends SIGTERM to the
Andrew M. Kuchling64c6a0e2008-04-21 02:08:00 +0000443 child. On Windows the Win32 API function :cfunc:`TerminateProcess` is called
Christian Heimese74c8f22008-04-19 02:23:57 +0000444 to stop the child.
445
Georg Brandl734de682008-04-19 08:23:59 +0000446 .. versionadded:: 2.6
447
Christian Heimese74c8f22008-04-19 02:23:57 +0000448
449.. method:: Popen.kill()
450
451 Kills the child. On Posix OSs the function sends SIGKILL to the child.
Georg Brandl734de682008-04-19 08:23:59 +0000452 On Windows :meth:`kill` is an alias for :meth:`terminate`.
453
454 .. versionadded:: 2.6
Christian Heimese74c8f22008-04-19 02:23:57 +0000455
456
Georg Brandl8ec7f652007-08-15 14:28:01 +0000457The following attributes are also available:
458
Georg Brandl143de622008-08-04 06:29:36 +0000459.. warning::
460
Georg Brandl16a57f62009-04-27 15:29:09 +0000461 Use :meth:`communicate` rather than :attr:`.stdin.write <stdin>`,
462 :attr:`.stdout.read <stdout>` or :attr:`.stderr.read <stderr>` to avoid
463 deadlocks due to any of the other OS pipe buffers filling up and blocking the
464 child process.
Georg Brandl143de622008-08-04 06:29:36 +0000465
466
Georg Brandl8ec7f652007-08-15 14:28:01 +0000467.. attribute:: Popen.stdin
468
Georg Brandlf5d5a662008-12-06 11:57:12 +0000469 If the *stdin* argument was :data:`PIPE`, this attribute is a file object
470 that provides input to the child process. Otherwise, it is ``None``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000471
472
473.. attribute:: Popen.stdout
474
Georg Brandlf5d5a662008-12-06 11:57:12 +0000475 If the *stdout* argument was :data:`PIPE`, this attribute is a file object
476 that provides output from the child process. Otherwise, it is ``None``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000477
478
479.. attribute:: Popen.stderr
480
Georg Brandlf5d5a662008-12-06 11:57:12 +0000481 If the *stderr* argument was :data:`PIPE`, this attribute is a file object
482 that provides error output from the child process. Otherwise, it is
483 ``None``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000484
485
486.. attribute:: Popen.pid
487
488 The process ID of the child process.
489
Georg Brandl0b56ce02010-03-21 09:28:16 +0000490 Note that if you set the *shell* argument to ``True``, this is the process ID
491 of the spawned shell.
492
Georg Brandl8ec7f652007-08-15 14:28:01 +0000493
494.. attribute:: Popen.returncode
495
Georg Brandl2cb103f2008-01-06 16:01:26 +0000496 The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly
497 by :meth:`communicate`). A ``None`` value indicates that the process
498 hasn't terminated yet.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000499
Georg Brandl2cb103f2008-01-06 16:01:26 +0000500 A negative value ``-N`` indicates that the child was terminated by signal
501 ``N`` (Unix only).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000502
503
Brian Curtinbb23bd62011-04-29 22:23:46 -0500504Windows Popen Helpers
505---------------------
506
507The :class:`STARTUPINFO` class and following constants are only available
508on Windows.
509
510.. class:: STARTUPINFO()
511
512 Partial support of the Windows
513 `STARTUPINFO <http://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx>`__
514 structure is used for :class:`Popen` creation.
515
516 .. attribute:: dwFlags
517
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700518 A bit field that determines whether certain :class:`STARTUPINFO`
519 attributes are used when the process creates a window. ::
Brian Curtinbb23bd62011-04-29 22:23:46 -0500520
521 si = subprocess.STARTUPINFO()
522 si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
523
524 .. attribute:: hStdInput
525
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700526 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
527 is the standard input handle for the process. If
528 :data:`STARTF_USESTDHANDLES` is not specified, the default for standard
529 input is the keyboard buffer.
Brian Curtinbb23bd62011-04-29 22:23:46 -0500530
531 .. attribute:: hStdOutput
532
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700533 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
534 is the standard output handle for the process. Otherwise, this attribute
535 is ignored and the default for standard output is the console window's
Brian Curtinbb23bd62011-04-29 22:23:46 -0500536 buffer.
537
538 .. attribute:: hStdError
539
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700540 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
541 is the standard error handle for the process. Otherwise, this attribute is
Brian Curtinbb23bd62011-04-29 22:23:46 -0500542 ignored and the default for standard error is the console window's buffer.
543
544 .. attribute:: wShowWindow
545
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700546 If :attr:`dwFlags` specifies :data:`STARTF_USESHOWWINDOW`, this attribute
Brian Curtinbb23bd62011-04-29 22:23:46 -0500547 can be any of the values that can be specified in the ``nCmdShow``
548 parameter for the
549 `ShowWindow <http://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx>`__
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700550 function, except for ``SW_SHOWDEFAULT``. Otherwise, this attribute is
Brian Curtinbb23bd62011-04-29 22:23:46 -0500551 ignored.
552
553 :data:`SW_HIDE` is provided for this attribute. It is used when
554 :class:`Popen` is called with ``shell=True``.
555
556
557Constants
558^^^^^^^^^
559
560The :mod:`subprocess` module exposes the following constants.
561
562.. data:: STD_INPUT_HANDLE
563
564 The standard input device. Initially, this is the console input buffer,
565 ``CONIN$``.
566
567.. data:: STD_OUTPUT_HANDLE
568
569 The standard output device. Initially, this is the active console screen
570 buffer, ``CONOUT$``.
571
572.. data:: STD_ERROR_HANDLE
573
574 The standard error device. Initially, this is the active console screen
575 buffer, ``CONOUT$``.
576
577.. data:: SW_HIDE
578
579 Hides the window. Another window will be activated.
580
581.. data:: STARTF_USESTDHANDLES
582
583 Specifies that the :attr:`STARTUPINFO.hStdInput`,
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700584 :attr:`STARTUPINFO.hStdOutput`, and :attr:`STARTUPINFO.hStdError` attributes
Brian Curtinbb23bd62011-04-29 22:23:46 -0500585 contain additional information.
586
587.. data:: STARTF_USESHOWWINDOW
588
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700589 Specifies that the :attr:`STARTUPINFO.wShowWindow` attribute contains
Brian Curtinbb23bd62011-04-29 22:23:46 -0500590 additional information.
591
592.. data:: CREATE_NEW_CONSOLE
593
594 The new process has a new console, instead of inheriting its parent's
595 console (the default).
596
597 This flag is always set when :class:`Popen` is created with ``shell=True``.
598
599.. data:: CREATE_NEW_PROCESS_GROUP
600
601 A :class:`Popen` ``creationflags`` parameter to specify that a new process
602 group will be created. This flag is necessary for using :func:`os.kill`
603 on the subprocess.
604
605 This flag is ignored if :data:`CREATE_NEW_CONSOLE` is specified.
606
607
Georg Brandl0ba92b22008-06-22 09:05:29 +0000608.. _subprocess-replacements:
609
Georg Brandl8ec7f652007-08-15 14:28:01 +0000610Replacing Older Functions with the subprocess Module
611----------------------------------------------------
612
Nick Coghlan86711572011-10-24 22:19:40 +1000613In this section, "a becomes b" means that b can be used as a replacement for a.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000614
615.. note::
616
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000617 All "a" functions in this section fail (more or less) silently if the
618 executed program cannot be found; the "b" replacements raise :exc:`OSError`
619 instead.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000620
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000621 In addition, the replacements using :func:`check_output` will fail with a
622 :exc:`CalledProcessError` if the requested operation produces a non-zero
623 return code. The output is still available as the ``output`` attribute of
624 the raised exception.
625
626In the following examples, we assume that the relevant functions have already
627been imported from the subprocess module.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000628
629
630Replacing /bin/sh shell backquote
631^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
632
633::
634
635 output=`mycmd myarg`
Nick Coghlan86711572011-10-24 22:19:40 +1000636 # becomes
637 output = check_output(["mycmd", "myarg"])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000638
639
Benjamin Petersoncae58482008-10-10 20:38:49 +0000640Replacing shell pipeline
641^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +0000642
643::
644
645 output=`dmesg | grep hda`
Nick Coghlan86711572011-10-24 22:19:40 +1000646 # becomes
Georg Brandl8ec7f652007-08-15 14:28:01 +0000647 p1 = Popen(["dmesg"], stdout=PIPE)
648 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Gregory P. Smithe3e967f2011-02-05 21:49:56 +0000649 p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000650 output = p2.communicate()[0]
651
Gregory P. Smithe3e967f2011-02-05 21:49:56 +0000652The p1.stdout.close() call after starting the p2 is important in order for p1
653to receive a SIGPIPE if p2 exits before p1.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000654
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000655Alternatively, for trusted input, the shell's own pipeline support may still
656be used directly:
Nick Coghlan86711572011-10-24 22:19:40 +1000657
658 output=`dmesg | grep hda`
659 # becomes
660 output=check_output("dmesg | grep hda", shell=True)
661
662
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000663Replacing :func:`os.system`
664^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +0000665
666::
667
668 sts = os.system("mycmd" + " myarg")
Nick Coghlan86711572011-10-24 22:19:40 +1000669 # becomes
670 sts = call("mycmd" + " myarg", shell=True)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000671
672Notes:
673
674* Calling the program through the shell is usually not required.
675
Georg Brandl8ec7f652007-08-15 14:28:01 +0000676A more realistic example would look like this::
677
678 try:
679 retcode = call("mycmd" + " myarg", shell=True)
680 if retcode < 0:
681 print >>sys.stderr, "Child was terminated by signal", -retcode
682 else:
683 print >>sys.stderr, "Child returned", retcode
684 except OSError, e:
685 print >>sys.stderr, "Execution failed:", e
686
687
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000688Replacing the :func:`os.spawn <os.spawnl>` family
689^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +0000690
691P_NOWAIT example::
692
693 pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
694 ==>
695 pid = Popen(["/bin/mycmd", "myarg"]).pid
696
697P_WAIT example::
698
699 retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
700 ==>
701 retcode = call(["/bin/mycmd", "myarg"])
702
703Vector example::
704
705 os.spawnvp(os.P_NOWAIT, path, args)
706 ==>
707 Popen([path] + args[1:])
708
709Environment example::
710
711 os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
712 ==>
713 Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
714
715
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000716Replacing :func:`os.popen`, :func:`os.popen2`, :func:`os.popen3`
717^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +0000718
719::
720
Philip Jenvey8b902042009-09-29 19:10:15 +0000721 pipe = os.popen("cmd", 'r', bufsize)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000722 ==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000723 pipe = Popen("cmd", shell=True, bufsize=bufsize, stdout=PIPE).stdout
Georg Brandl8ec7f652007-08-15 14:28:01 +0000724
725::
726
Philip Jenvey8b902042009-09-29 19:10:15 +0000727 pipe = os.popen("cmd", 'w', bufsize)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000728 ==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000729 pipe = Popen("cmd", shell=True, bufsize=bufsize, stdin=PIPE).stdin
Georg Brandl8ec7f652007-08-15 14:28:01 +0000730
731::
732
Philip Jenvey8b902042009-09-29 19:10:15 +0000733 (child_stdin, child_stdout) = os.popen2("cmd", mode, bufsize)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000734 ==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000735 p = Popen("cmd", shell=True, bufsize=bufsize,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000736 stdin=PIPE, stdout=PIPE, close_fds=True)
737 (child_stdin, child_stdout) = (p.stdin, p.stdout)
738
739::
740
741 (child_stdin,
742 child_stdout,
Philip Jenvey8b902042009-09-29 19:10:15 +0000743 child_stderr) = os.popen3("cmd", mode, bufsize)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000744 ==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000745 p = Popen("cmd", shell=True, bufsize=bufsize,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000746 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
747 (child_stdin,
748 child_stdout,
749 child_stderr) = (p.stdin, p.stdout, p.stderr)
750
751::
752
Philip Jenvey8b902042009-09-29 19:10:15 +0000753 (child_stdin, child_stdout_and_stderr) = os.popen4("cmd", mode,
754 bufsize)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000755 ==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000756 p = Popen("cmd", shell=True, bufsize=bufsize,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000757 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
758 (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
759
Philip Jenvey8b902042009-09-29 19:10:15 +0000760On Unix, os.popen2, os.popen3 and os.popen4 also accept a sequence as
761the command to execute, in which case arguments will be passed
762directly to the program without shell intervention. This usage can be
763replaced as follows::
764
765 (child_stdin, child_stdout) = os.popen2(["/bin/ls", "-l"], mode,
766 bufsize)
767 ==>
768 p = Popen(["/bin/ls", "-l"], bufsize=bufsize, stdin=PIPE, stdout=PIPE)
769 (child_stdin, child_stdout) = (p.stdin, p.stdout)
770
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000771Return code handling translates as follows::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000772
Philip Jenvey8b902042009-09-29 19:10:15 +0000773 pipe = os.popen("cmd", 'w')
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000774 ...
775 rc = pipe.close()
Stefan Kraha253dc12010-07-14 10:06:07 +0000776 if rc is not None and rc >> 8:
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000777 print "There were some errors"
778 ==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000779 process = Popen("cmd", 'w', shell=True, stdin=PIPE)
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000780 ...
781 process.stdin.close()
782 if process.wait() != 0:
783 print "There were some errors"
784
785
786Replacing functions from the :mod:`popen2` module
787^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +0000788
Georg Brandl8ec7f652007-08-15 14:28:01 +0000789::
790
791 (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
792 ==>
793 p = Popen(["somestring"], shell=True, bufsize=bufsize,
794 stdin=PIPE, stdout=PIPE, close_fds=True)
795 (child_stdout, child_stdin) = (p.stdout, p.stdin)
796
Philip Jenvey8b902042009-09-29 19:10:15 +0000797On Unix, popen2 also accepts a sequence as the command to execute, in
798which case arguments will be passed directly to the program without
799shell intervention. This usage can be replaced as follows::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000800
Philip Jenvey8b902042009-09-29 19:10:15 +0000801 (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize,
802 mode)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000803 ==>
804 p = Popen(["mycmd", "myarg"], bufsize=bufsize,
805 stdin=PIPE, stdout=PIPE, close_fds=True)
806 (child_stdout, child_stdin) = (p.stdout, p.stdin)
807
Georg Brandlf5d5a662008-12-06 11:57:12 +0000808:class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as
809:class:`subprocess.Popen`, except that:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000810
Georg Brandlf5d5a662008-12-06 11:57:12 +0000811* :class:`Popen` raises an exception if the execution fails.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000812
813* the *capturestderr* argument is replaced with the *stderr* argument.
814
Georg Brandlf5d5a662008-12-06 11:57:12 +0000815* ``stdin=PIPE`` and ``stdout=PIPE`` must be specified.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000816
817* popen2 closes all file descriptors by default, but you have to specify
Georg Brandlf5d5a662008-12-06 11:57:12 +0000818 ``close_fds=True`` with :class:`Popen`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000819
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000820
Eli Bendersky929e2762011-04-15 07:35:06 +0300821Notes
822-----
823
824.. _converting-argument-sequence:
825
826Converting an argument sequence to a string on Windows
827^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
828
829On Windows, an *args* sequence is converted to a string that can be parsed
830using the following rules (which correspond to the rules used by the MS C
831runtime):
832
8331. Arguments are delimited by white space, which is either a
834 space or a tab.
835
8362. A string surrounded by double quotation marks is
837 interpreted as a single argument, regardless of white space
838 contained within. A quoted string can be embedded in an
839 argument.
840
8413. A double quotation mark preceded by a backslash is
842 interpreted as a literal double quotation mark.
843
8444. Backslashes are interpreted literally, unless they
845 immediately precede a double quotation mark.
846
8475. If backslashes immediately precede a double quotation mark,
848 every pair of backslashes is interpreted as a literal
849 backslash. If the number of backslashes is odd, the last
850 backslash escapes the next double quotation mark as
851 described in rule 3.
852