blob: c92a43fd3c1fb20f4265b202fe70f717439ed223 [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
Ezio Melotti26025d62012-11-08 10:07:10 +020031Using the :mod:`subprocess` Module
32----------------------------------
Georg Brandl8ec7f652007-08-15 14:28:01 +000033
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
Nick Coghlan87ba6422011-10-27 17:55:13 +100045 in :ref:`frequently-used-arguments` (hence the slightly odd notation in
46 the abbreviated signature). The full function signature is the same as
47 that of the :class:`Popen` constructor - this functions passes all
48 supplied arguments directly through to that interface.
Nick Coghlan86711572011-10-24 22:19:40 +100049
50 Examples::
51
52 >>> subprocess.call(["ls", "-l"])
53 0
54
Nick Coghlan2ed203a2011-10-26 21:05:56 +100055 >>> subprocess.call("exit 1", shell=True)
Nick Coghlan86711572011-10-24 22:19:40 +100056 1
57
58 .. warning::
59
Nick Coghlan87ba6422011-10-27 17:55:13 +100060 Invoking the system shell with ``shell=True`` can be a security hazard
61 if combined with untrusted input. See the warning under
62 :ref:`frequently-used-arguments` for details.
63
64 .. note::
65
Nick Coghlan2ed203a2011-10-26 21:05:56 +100066 Do not use ``stdout=PIPE`` or ``stderr=PIPE`` with this function. As
67 the pipes are not being read in the current process, the child
68 process may block if it generates enough output to a pipe to fill up
69 the OS pipe buffer.
Nick Coghlan86711572011-10-24 22:19:40 +100070
71
Nick Coghlan87ba6422011-10-27 17:55:13 +100072.. function:: check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
Nick Coghlan86711572011-10-24 22:19:40 +100073
74 Run command with arguments. Wait for command to complete. If the return
75 code was zero then return, otherwise raise :exc:`CalledProcessError`. The
76 :exc:`CalledProcessError` object will have the return code in the
Serhiy Storchakac8f26f52013-08-24 00:28:38 +030077 :attr:`~CalledProcessError.returncode` attribute.
Nick Coghlan86711572011-10-24 22:19:40 +100078
Nick Coghlan87ba6422011-10-27 17:55:13 +100079 The arguments shown above are merely the most common ones, described below
80 in :ref:`frequently-used-arguments` (hence the slightly odd notation in
81 the abbreviated signature). The full function signature is the same as
82 that of the :class:`Popen` constructor - this functions passes all
83 supplied arguments directly through to that interface.
84
85 Examples::
Nick Coghlan86711572011-10-24 22:19:40 +100086
87 >>> subprocess.check_call(["ls", "-l"])
88 0
89
Nick Coghlan2ed203a2011-10-26 21:05:56 +100090 >>> subprocess.check_call("exit 1", shell=True)
Nick Coghlan86711572011-10-24 22:19:40 +100091 Traceback (most recent call last):
92 ...
Nick Coghlan2ed203a2011-10-26 21:05:56 +100093 subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
Nick Coghlan86711572011-10-24 22:19:40 +100094
95 .. versionadded:: 2.5
96
97 .. warning::
98
Nick Coghlan87ba6422011-10-27 17:55:13 +100099 Invoking the system shell with ``shell=True`` can be a security hazard
100 if combined with untrusted input. See the warning under
101 :ref:`frequently-used-arguments` for details.
102
103 .. note::
104
105 Do not use ``stdout=PIPE`` or ``stderr=PIPE`` with this function. As
106 the pipes are not being read in the current process, the child
107 process may block if it generates enough output to a pipe to fill up
108 the OS pipe buffer.
Nick Coghlan86711572011-10-24 22:19:40 +1000109
110
Nick Coghlan87ba6422011-10-27 17:55:13 +1000111.. function:: check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
Nick Coghlan86711572011-10-24 22:19:40 +1000112
113 Run command with arguments and return its output as a byte string.
114
115 If the return code was non-zero it raises a :exc:`CalledProcessError`. The
116 :exc:`CalledProcessError` object will have the return code in the
Serhiy Storchakac8f26f52013-08-24 00:28:38 +0300117 :attr:`~CalledProcessError.returncode` attribute and any output in the
118 :attr:`~CalledProcessError.output` attribute.
Nick Coghlan86711572011-10-24 22:19:40 +1000119
Nick Coghlan87ba6422011-10-27 17:55:13 +1000120 The arguments shown above are merely the most common ones, described below
121 in :ref:`frequently-used-arguments` (hence the slightly odd notation in
122 the abbreviated signature). The full function signature is largely the
123 same as that of the :class:`Popen` constructor, except that *stdout* is
124 not permitted as it is used internally. All other supplied arguments are
125 passed directly through to the :class:`Popen` constructor.
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000126
Nick Coghlan86711572011-10-24 22:19:40 +1000127 Examples::
128
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000129 >>> subprocess.check_output(["echo", "Hello World!"])
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000130 'Hello World!\n'
131
132 >>> subprocess.check_output("exit 1", shell=True)
Nick Coghlan86711572011-10-24 22:19:40 +1000133 Traceback (most recent call last):
134 ...
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000135 subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
Nick Coghlan86711572011-10-24 22:19:40 +1000136
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000137 To also capture standard error in the result, use
138 ``stderr=subprocess.STDOUT``::
Nick Coghlan86711572011-10-24 22:19:40 +1000139
140 >>> subprocess.check_output(
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000141 ... "ls non_existent_file; exit 0",
142 ... stderr=subprocess.STDOUT,
143 ... shell=True)
Nick Coghlan86711572011-10-24 22:19:40 +1000144 'ls: non_existent_file: No such file or directory\n'
145
146 .. versionadded:: 2.7
147
Georg Brandl44ea77b2013-03-28 13:28:44 +0100148 ..
149
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000150 .. warning::
151
Nick Coghlan87ba6422011-10-27 17:55:13 +1000152 Invoking the system shell with ``shell=True`` can be a security hazard
153 if combined with untrusted input. See the warning under
154 :ref:`frequently-used-arguments` for details.
155
156 .. note::
157
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000158 Do not use ``stderr=PIPE`` with this function. As the pipe is not being
159 read in the current process, the child process may block if it
160 generates enough output to the pipe to fill up the OS pipe buffer.
161
Nick Coghlan86711572011-10-24 22:19:40 +1000162
163.. data:: PIPE
164
165 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
166 to :class:`Popen` and indicates that a pipe to the standard stream should be
167 opened.
168
169
170.. data:: STDOUT
171
172 Special value that can be used as the *stderr* argument to :class:`Popen` and
173 indicates that standard error should go into the same handle as standard
174 output.
175
176
Andrew Svetlov8afcec42012-08-09 15:23:49 +0300177.. exception:: CalledProcessError
178
179 Exception raised when a process run by :func:`check_call` or
180 :func:`check_output` returns a non-zero exit status.
181
182 .. attribute:: returncode
183
184 Exit status of the child process.
185
186 .. attribute:: cmd
187
188 Command that was used to spawn the child process.
189
190 .. attribute:: output
191
192 Output of the child process if this exception is raised by
193 :func:`check_output`. Otherwise, ``None``.
194
195
196
Nick Coghlan86711572011-10-24 22:19:40 +1000197.. _frequently-used-arguments:
198
199Frequently Used Arguments
200^^^^^^^^^^^^^^^^^^^^^^^^^
201
202To support a wide variety of use cases, the :class:`Popen` constructor (and
203the convenience functions) accept a large number of optional arguments. For
204most typical use cases, many of these arguments can be safely left at their
205default values. The arguments that are most commonly needed are:
206
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000207 *args* is required for all calls and should be a string, or a sequence of
208 program arguments. Providing a sequence of arguments is generally
209 preferred, as it allows the module to take care of any required escaping
210 and quoting of arguments (e.g. to permit spaces in file names). If passing
211 a single string, either *shell* must be :const:`True` (see below) or else
212 the string must simply name the program to be executed without specifying
213 any arguments.
Nick Coghlan86711572011-10-24 22:19:40 +1000214
215 *stdin*, *stdout* and *stderr* specify the executed program's standard input,
216 standard output and standard error file handles, respectively. Valid values
217 are :data:`PIPE`, an existing file descriptor (a positive integer), an
218 existing file object, and ``None``. :data:`PIPE` indicates that a new pipe
219 to the child should be created. With the default settings of ``None``, no
220 redirection will occur; the child's file handles will be inherited from the
221 parent. Additionally, *stderr* can be :data:`STDOUT`, which indicates that
222 the stderr data from the child process should be captured into the same file
223 handle as for stdout.
224
R David Murray5618aaa2012-08-15 11:15:39 -0400225 .. index::
226 single: universal newlines; subprocess module
227
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000228 When *stdout* or *stderr* are pipes and *universal_newlines* is
R David Murray5618aaa2012-08-15 11:15:39 -0400229 ``True`` then all line endings will be converted to ``'\n'`` as described
Ezio Melotti93324d72013-03-28 05:47:31 +0200230 for the :term:`universal newlines` ``'U'`` mode argument to :func:`open`.
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000231
Ezio Melottieab4df52012-09-15 08:33:12 +0300232 If *shell* is ``True``, the specified command will be executed through
233 the shell. This can be useful if you are using Python primarily for the
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000234 enhanced control flow it offers over most system shells and still want
Ezio Melottieab4df52012-09-15 08:33:12 +0300235 convenient access to other shell features such as shell pipes, filename
236 wildcards, environment variable expansion, and expansion of ``~`` to a
237 user's home directory. However, note that Python itself offers
238 implementations of many shell-like features (in particular, :mod:`glob`,
239 :mod:`fnmatch`, :func:`os.walk`, :func:`os.path.expandvars`,
240 :func:`os.path.expanduser`, and :mod:`shutil`).
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000241
242 .. warning::
243
244 Executing shell commands that incorporate unsanitized input from an
245 untrusted source makes a program vulnerable to `shell injection
246 <http://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_,
247 a serious security flaw which can result in arbitrary command execution.
Chris Jerdonek1e651592012-10-10 22:58:57 -0700248 For this reason, the use of ``shell=True`` is **strongly discouraged**
249 in cases where the command string is constructed from external input::
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000250
251 >>> from subprocess import call
252 >>> filename = input("What file would you like to display?\n")
253 What file would you like to display?
254 non_existent; rm -rf / #
255 >>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...
256
257 ``shell=False`` disables all shell based features, but does not suffer
258 from this vulnerability; see the Note in the :class:`Popen` constructor
259 documentation for helpful hints in getting ``shell=False`` to work.
260
Andrew Svetlov61822662012-10-28 11:48:02 +0200261 When using ``shell=True``, :func:`pipes.quote` can be used to properly
262 escape whitespace and shell metacharacters in strings that are going to
263 be used to construct shell commands.
264
Nick Coghlan86711572011-10-24 22:19:40 +1000265These options, along with all of the other options, are described in more
266detail in the :class:`Popen` constructor documentation.
267
268
Sandro Tosidbcbd102011-12-25 11:27:22 +0100269Popen Constructor
Sandro Tosi44585bd2011-12-25 17:13:10 +0100270^^^^^^^^^^^^^^^^^
Nick Coghlan86711572011-10-24 22:19:40 +1000271
272The underlying process creation and management in this module is handled by
273the :class:`Popen` class. It offers a lot of flexibility so that developers
274are able to handle the less common cases not covered by the convenience
275functions.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000276
277
Chris Jerdonek2a6672b2012-10-10 17:55:41 -0700278.. class:: Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, \
279 stderr=None, preexec_fn=None, close_fds=False, shell=False, \
280 cwd=None, env=None, universal_newlines=False, \
281 startupinfo=None, creationflags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000282
Chris Jerdonek2a6672b2012-10-10 17:55:41 -0700283 Execute a child program in a new process. On Unix, the class uses
284 :meth:`os.execvp`-like behavior to execute the child program. On Windows,
285 the class uses the Windows ``CreateProcess()`` function. The arguments to
286 :class:`Popen` are as follows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000287
Chris Jerdonek1906c0c2012-10-08 23:18:17 -0700288 *args* should be a sequence of program arguments or else a single string.
289 By default, the program to execute is the first item in *args* if *args* is
Chris Jerdonek2a6672b2012-10-10 17:55:41 -0700290 a sequence. If *args* is a string, the interpretation is
291 platform-dependent and described below. See the *shell* and *executable*
292 arguments for additional differences from the default behavior. Unless
293 otherwise stated, it is recommended to pass *args* as a sequence.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000294
Chris Jerdonek2a6672b2012-10-10 17:55:41 -0700295 On Unix, if *args* is a string, the string is interpreted as the name or
296 path of the program to execute. However, this can only be done if not
297 passing arguments to the program.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000298
Nick Coghlan7dfc9e12010-02-04 12:43:58 +0000299 .. note::
300
301 :meth:`shlex.split` can be useful when determining the correct
302 tokenization for *args*, especially in complex cases::
303
304 >>> import shlex, subprocess
305 >>> command_line = raw_input()
306 /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
307 >>> args = shlex.split(command_line)
308 >>> print args
309 ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
310 >>> p = subprocess.Popen(args) # Success!
311
312 Note in particular that options (such as *-input*) and arguments (such
313 as *eggs.txt*) that are separated by whitespace in the shell go in separate
314 list elements, while arguments that need quoting or backslash escaping when
315 used in the shell (such as filenames containing spaces or the *echo* command
316 shown above) are single list elements.
317
Chris Jerdonek2a6672b2012-10-10 17:55:41 -0700318 On Windows, if *args* is a sequence, it will be converted to a string in a
319 manner described in :ref:`converting-argument-sequence`. This is because
320 the underlying ``CreateProcess()`` operates on strings.
Chris Jerdonek1906c0c2012-10-08 23:18:17 -0700321
322 The *shell* argument (which defaults to *False*) specifies whether to use
Chris Jerdonek2a6672b2012-10-10 17:55:41 -0700323 the shell as the program to execute. If *shell* is *True*, it is
324 recommended to pass *args* as a string rather than as a sequence.
Chris Jerdonek1906c0c2012-10-08 23:18:17 -0700325
326 On Unix with ``shell=True``, the shell defaults to :file:`/bin/sh`. If
327 *args* is a string, the string specifies the command
328 to execute through the shell. This means that the string must be
Nick Coghlan7dfc9e12010-02-04 12:43:58 +0000329 formatted exactly as it would be when typed at the shell prompt. This
330 includes, for example, quoting or backslash escaping filenames with spaces in
331 them. If *args* is a sequence, the first item specifies the command string, and
332 any additional items will be treated as additional arguments to the shell
Chris Jerdonek1906c0c2012-10-08 23:18:17 -0700333 itself. That is to say, :class:`Popen` does the equivalent of::
Nick Coghlan7dfc9e12010-02-04 12:43:58 +0000334
335 Popen(['/bin/sh', '-c', args[0], args[1], ...])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000336
Chris Jerdonek1906c0c2012-10-08 23:18:17 -0700337 On Windows with ``shell=True``, the :envvar:`COMSPEC` environment variable
338 specifies the default shell. The only time you need to specify
339 ``shell=True`` on Windows is when the command you wish to execute is built
340 into the shell (e.g. :command:`dir` or :command:`copy`). You do not need
341 ``shell=True`` to run a batch file or console-based executable.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000342
Chris Jerdonek1e651592012-10-10 22:58:57 -0700343 .. warning::
344
345 Passing ``shell=True`` can be a security hazard if combined with
346 untrusted input. See the warning under :ref:`frequently-used-arguments`
347 for details.
348
Georg Brandl8ec7f652007-08-15 14:28:01 +0000349 *bufsize*, if given, has the same meaning as the corresponding argument to the
350 built-in open() function: :const:`0` means unbuffered, :const:`1` means line
351 buffered, any other positive value means use a buffer of (approximately) that
352 size. A negative *bufsize* means to use the system default, which usually means
353 fully buffered. The default value for *bufsize* is :const:`0` (unbuffered).
354
Antoine Pitrouc3955452010-06-02 17:08:47 +0000355 .. note::
356
357 If you experience performance issues, it is recommended that you try to
358 enable buffering by setting *bufsize* to either -1 or a large enough
359 positive value (such as 4096).
360
Chris Jerdonek1906c0c2012-10-08 23:18:17 -0700361 The *executable* argument specifies a replacement program to execute. It
362 is very seldom needed. When ``shell=False``, *executable* replaces the
Chris Jerdonek2a6672b2012-10-10 17:55:41 -0700363 program to execute specified by *args*. However, the original *args* is
364 still passed to the program. Most programs treat the program specified
365 by *args* as the command name, which can then be different from the program
366 actually executed. On Unix, the *args* name
Chris Jerdonek1906c0c2012-10-08 23:18:17 -0700367 becomes the display name for the executable in utilities such as
368 :program:`ps`. If ``shell=True``, on Unix the *executable* argument
369 specifies a replacement shell for the default :file:`/bin/sh`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000370
Nick Coghlan86711572011-10-24 22:19:40 +1000371 *stdin*, *stdout* and *stderr* specify the executed program's standard input,
Georg Brandlf5d5a662008-12-06 11:57:12 +0000372 standard output and standard error file handles, respectively. Valid values
373 are :data:`PIPE`, an existing file descriptor (a positive integer), an
374 existing file object, and ``None``. :data:`PIPE` indicates that a new pipe
Nick Coghlan86711572011-10-24 22:19:40 +1000375 to the child should be created. With the default settings of ``None``, no
376 redirection will occur; the child's file handles will be inherited from the
377 parent. Additionally, *stderr* can be :data:`STDOUT`, which indicates that
378 the stderr data from the child process should be captured into the same file
379 handle as for stdout.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000380
381 If *preexec_fn* is set to a callable object, this object will be called in the
382 child process just before the child is executed. (Unix only)
383
384 If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and
385 :const:`2` will be closed before the child process is executed. (Unix only).
386 Or, on Windows, if *close_fds* is true then no handles will be inherited by the
387 child process. Note that on Windows, you cannot set *close_fds* to true and
388 also redirect the standard handles by setting *stdin*, *stdout* or *stderr*.
389
Georg Brandl8ec7f652007-08-15 14:28:01 +0000390 If *cwd* is not ``None``, the child's current directory will be changed to *cwd*
391 before it is executed. Note that this directory is not considered when
392 searching the executable, so you can't specify the program's path relative to
393 *cwd*.
394
Georg Brandlf801b0f2008-04-19 16:58:49 +0000395 If *env* is not ``None``, it must be a mapping that defines the environment
396 variables for the new process; these are used instead of inheriting the current
397 process' environment, which is the default behavior.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000398
R. David Murray72030812009-04-16 18:12:53 +0000399 .. note::
R. David Murray6076d392009-04-15 22:33:07 +0000400
R. David Murray72030812009-04-16 18:12:53 +0000401 If specified, *env* must provide any variables required
402 for the program to execute. On Windows, in order to run a
403 `side-by-side assembly`_ the specified *env* **must** include a valid
R. David Murray6076d392009-04-15 22:33:07 +0000404 :envvar:`SystemRoot`.
405
R. David Murray72030812009-04-16 18:12:53 +0000406 .. _side-by-side assembly: http://en.wikipedia.org/wiki/Side-by-Side_Assembly
407
R David Murrayc7b8f802012-08-15 11:22:58 -0400408 If *universal_newlines* is ``True``, the file objects *stdout* and *stderr*
409 are opened as text files in :term:`universal newlines` mode. Lines may be
410 terminated by any of ``'\n'``, the Unix end-of-line convention, ``'\r'``,
411 the old Macintosh convention or ``'\r\n'``, the Windows convention. All of
412 these external representations are seen as ``'\n'`` by the Python program.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000413
414 .. note::
415
Georg Brandl6ab5d082009-12-20 14:33:20 +0000416 This feature is only available if Python is built with universal newline
417 support (the default). Also, the newlines attribute of the file objects
418 :attr:`stdout`, :attr:`stdin` and :attr:`stderr` are not updated by the
419 communicate() method.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000420
Brian Curtinbb23bd62011-04-29 22:23:46 -0500421 If given, *startupinfo* will be a :class:`STARTUPINFO` object, which is
422 passed to the underlying ``CreateProcess`` function.
423 *creationflags*, if given, can be :data:`CREATE_NEW_CONSOLE` or
424 :data:`CREATE_NEW_PROCESS_GROUP`. (Windows only)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000425
426
Georg Brandl8ec7f652007-08-15 14:28:01 +0000427Exceptions
428^^^^^^^^^^
429
430Exceptions raised in the child process, before the new program has started to
431execute, will be re-raised in the parent. Additionally, the exception object
432will have one extra attribute called :attr:`child_traceback`, which is a string
Georg Brandl21946af2010-10-06 09:28:45 +0000433containing traceback information from the child's point of view.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000434
435The most common exception raised is :exc:`OSError`. This occurs, for example,
436when trying to execute a non-existent file. Applications should prepare for
437:exc:`OSError` exceptions.
438
439A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid
440arguments.
441
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000442:func:`check_call` and :func:`check_output` will raise
443:exc:`CalledProcessError` if the called process returns a non-zero return
444code.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000445
446
447Security
448^^^^^^^^
449
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000450Unlike some other popen functions, this implementation will never call a
451system shell implicitly. This means that all characters, including shell
452metacharacters, can safely be passed to child processes. Obviously, if the
453shell is invoked explicitly, then it is the application's responsibility to
Nick Coghlan63c54e82011-10-26 21:34:26 +1000454ensure that all whitespace and metacharacters are quoted appropriately.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000455
456
457Popen Objects
458-------------
459
460Instances of the :class:`Popen` class have the following methods:
461
462
463.. method:: Popen.poll()
464
Serhiy Storchakac8f26f52013-08-24 00:28:38 +0300465 Check if child process has terminated. Set and return
466 :attr:`~Popen.returncode` attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000467
468
469.. method:: Popen.wait()
470
Serhiy Storchakac8f26f52013-08-24 00:28:38 +0300471 Wait for child process to terminate. Set and return
472 :attr:`~Popen.returncode` attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000473
Georg Brandl143de622008-08-04 06:29:36 +0000474 .. warning::
475
Philip Jenvey26275532009-12-03 02:25:54 +0000476 This will deadlock when using ``stdout=PIPE`` and/or
477 ``stderr=PIPE`` and the child process generates enough output to
478 a pipe such that it blocks waiting for the OS pipe buffer to
479 accept more data. Use :meth:`communicate` to avoid that.
Gregory P. Smith08792502008-08-04 01:03:50 +0000480
Georg Brandl8ec7f652007-08-15 14:28:01 +0000481
482.. method:: Popen.communicate(input=None)
483
484 Interact with process: Send data to stdin. Read data from stdout and stderr,
485 until end-of-file is reached. Wait for process to terminate. The optional
486 *input* argument should be a string to be sent to the child process, or
487 ``None``, if no data should be sent to the child.
488
Georg Brandl17432012008-12-04 21:28:16 +0000489 :meth:`communicate` returns a tuple ``(stdoutdata, stderrdata)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000490
Georg Brandl439f2502007-11-24 11:31:46 +0000491 Note that if you want to send data to the process's stdin, you need to create
492 the Popen object with ``stdin=PIPE``. Similarly, to get anything other than
493 ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or
494 ``stderr=PIPE`` too.
495
Georg Brandl2cb103f2008-01-06 16:01:26 +0000496 .. note::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000497
Georg Brandl2cb103f2008-01-06 16:01:26 +0000498 The data read is buffered in memory, so do not use this method if the data
499 size is large or unlimited.
500
Georg Brandl8ec7f652007-08-15 14:28:01 +0000501
Christian Heimese74c8f22008-04-19 02:23:57 +0000502.. method:: Popen.send_signal(signal)
503
504 Sends the signal *signal* to the child.
505
506 .. note::
507
Brian Curtine5aa8862010-04-02 23:26:06 +0000508 On Windows, SIGTERM is an alias for :meth:`terminate`. CTRL_C_EVENT and
Ezio Melotti9ccc5812010-04-05 08:16:41 +0000509 CTRL_BREAK_EVENT can be sent to processes started with a *creationflags*
Brian Curtine5aa8862010-04-02 23:26:06 +0000510 parameter which includes `CREATE_NEW_PROCESS_GROUP`.
Georg Brandl734de682008-04-19 08:23:59 +0000511
512 .. versionadded:: 2.6
Christian Heimese74c8f22008-04-19 02:23:57 +0000513
514
515.. method:: Popen.terminate()
516
517 Stop the child. On Posix OSs the method sends SIGTERM to the
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100518 child. On Windows the Win32 API function :c:func:`TerminateProcess` is called
Christian Heimese74c8f22008-04-19 02:23:57 +0000519 to stop the child.
520
Georg Brandl734de682008-04-19 08:23:59 +0000521 .. versionadded:: 2.6
522
Christian Heimese74c8f22008-04-19 02:23:57 +0000523
524.. method:: Popen.kill()
525
526 Kills the child. On Posix OSs the function sends SIGKILL to the child.
Georg Brandl734de682008-04-19 08:23:59 +0000527 On Windows :meth:`kill` is an alias for :meth:`terminate`.
528
529 .. versionadded:: 2.6
Christian Heimese74c8f22008-04-19 02:23:57 +0000530
531
Georg Brandl8ec7f652007-08-15 14:28:01 +0000532The following attributes are also available:
533
Georg Brandl143de622008-08-04 06:29:36 +0000534.. warning::
535
Ezio Melotti8662c842012-08-27 10:00:05 +0300536 Use :meth:`~Popen.communicate` rather than :attr:`.stdin.write <Popen.stdin>`,
537 :attr:`.stdout.read <Popen.stdout>` or :attr:`.stderr.read <Popen.stderr>` to avoid
Georg Brandl16a57f62009-04-27 15:29:09 +0000538 deadlocks due to any of the other OS pipe buffers filling up and blocking the
539 child process.
Georg Brandl143de622008-08-04 06:29:36 +0000540
541
Georg Brandl8ec7f652007-08-15 14:28:01 +0000542.. attribute:: Popen.stdin
543
Georg Brandlf5d5a662008-12-06 11:57:12 +0000544 If the *stdin* argument was :data:`PIPE`, this attribute is a file object
545 that provides input to the child process. Otherwise, it is ``None``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000546
547
548.. attribute:: Popen.stdout
549
Georg Brandlf5d5a662008-12-06 11:57:12 +0000550 If the *stdout* argument was :data:`PIPE`, this attribute is a file object
551 that provides output from the child process. Otherwise, it is ``None``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000552
553
554.. attribute:: Popen.stderr
555
Georg Brandlf5d5a662008-12-06 11:57:12 +0000556 If the *stderr* argument was :data:`PIPE`, this attribute is a file object
557 that provides error output from the child process. Otherwise, it is
558 ``None``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000559
560
561.. attribute:: Popen.pid
562
563 The process ID of the child process.
564
Georg Brandl0b56ce02010-03-21 09:28:16 +0000565 Note that if you set the *shell* argument to ``True``, this is the process ID
566 of the spawned shell.
567
Georg Brandl8ec7f652007-08-15 14:28:01 +0000568
569.. attribute:: Popen.returncode
570
Georg Brandl2cb103f2008-01-06 16:01:26 +0000571 The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly
572 by :meth:`communicate`). A ``None`` value indicates that the process
573 hasn't terminated yet.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000574
Georg Brandl2cb103f2008-01-06 16:01:26 +0000575 A negative value ``-N`` indicates that the child was terminated by signal
576 ``N`` (Unix only).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000577
578
Brian Curtinbb23bd62011-04-29 22:23:46 -0500579Windows Popen Helpers
580---------------------
581
582The :class:`STARTUPINFO` class and following constants are only available
583on Windows.
584
585.. class:: STARTUPINFO()
586
587 Partial support of the Windows
588 `STARTUPINFO <http://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx>`__
589 structure is used for :class:`Popen` creation.
590
591 .. attribute:: dwFlags
592
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700593 A bit field that determines whether certain :class:`STARTUPINFO`
594 attributes are used when the process creates a window. ::
Brian Curtinbb23bd62011-04-29 22:23:46 -0500595
596 si = subprocess.STARTUPINFO()
597 si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
598
599 .. attribute:: hStdInput
600
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700601 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
602 is the standard input handle for the process. If
603 :data:`STARTF_USESTDHANDLES` is not specified, the default for standard
604 input is the keyboard buffer.
Brian Curtinbb23bd62011-04-29 22:23:46 -0500605
606 .. attribute:: hStdOutput
607
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700608 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
609 is the standard output handle for the process. Otherwise, this attribute
610 is ignored and the default for standard output is the console window's
Brian Curtinbb23bd62011-04-29 22:23:46 -0500611 buffer.
612
613 .. attribute:: hStdError
614
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700615 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
616 is the standard error handle for the process. Otherwise, this attribute is
Brian Curtinbb23bd62011-04-29 22:23:46 -0500617 ignored and the default for standard error is the console window's buffer.
618
619 .. attribute:: wShowWindow
620
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700621 If :attr:`dwFlags` specifies :data:`STARTF_USESHOWWINDOW`, this attribute
Brian Curtinbb23bd62011-04-29 22:23:46 -0500622 can be any of the values that can be specified in the ``nCmdShow``
623 parameter for the
624 `ShowWindow <http://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx>`__
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700625 function, except for ``SW_SHOWDEFAULT``. Otherwise, this attribute is
Brian Curtinbb23bd62011-04-29 22:23:46 -0500626 ignored.
627
628 :data:`SW_HIDE` is provided for this attribute. It is used when
629 :class:`Popen` is called with ``shell=True``.
630
631
632Constants
633^^^^^^^^^
634
635The :mod:`subprocess` module exposes the following constants.
636
637.. data:: STD_INPUT_HANDLE
638
639 The standard input device. Initially, this is the console input buffer,
640 ``CONIN$``.
641
642.. data:: STD_OUTPUT_HANDLE
643
644 The standard output device. Initially, this is the active console screen
645 buffer, ``CONOUT$``.
646
647.. data:: STD_ERROR_HANDLE
648
649 The standard error device. Initially, this is the active console screen
650 buffer, ``CONOUT$``.
651
652.. data:: SW_HIDE
653
654 Hides the window. Another window will be activated.
655
656.. data:: STARTF_USESTDHANDLES
657
658 Specifies that the :attr:`STARTUPINFO.hStdInput`,
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700659 :attr:`STARTUPINFO.hStdOutput`, and :attr:`STARTUPINFO.hStdError` attributes
Brian Curtinbb23bd62011-04-29 22:23:46 -0500660 contain additional information.
661
662.. data:: STARTF_USESHOWWINDOW
663
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700664 Specifies that the :attr:`STARTUPINFO.wShowWindow` attribute contains
Brian Curtinbb23bd62011-04-29 22:23:46 -0500665 additional information.
666
667.. data:: CREATE_NEW_CONSOLE
668
669 The new process has a new console, instead of inheriting its parent's
670 console (the default).
671
672 This flag is always set when :class:`Popen` is created with ``shell=True``.
673
674.. data:: CREATE_NEW_PROCESS_GROUP
675
676 A :class:`Popen` ``creationflags`` parameter to specify that a new process
677 group will be created. This flag is necessary for using :func:`os.kill`
678 on the subprocess.
679
680 This flag is ignored if :data:`CREATE_NEW_CONSOLE` is specified.
681
682
Georg Brandl0ba92b22008-06-22 09:05:29 +0000683.. _subprocess-replacements:
684
Ezio Melotti26025d62012-11-08 10:07:10 +0200685Replacing Older Functions with the :mod:`subprocess` Module
686-----------------------------------------------------------
Georg Brandl8ec7f652007-08-15 14:28:01 +0000687
Nick Coghlan86711572011-10-24 22:19:40 +1000688In this section, "a becomes b" means that b can be used as a replacement for a.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000689
690.. note::
691
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000692 All "a" functions in this section fail (more or less) silently if the
693 executed program cannot be found; the "b" replacements raise :exc:`OSError`
694 instead.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000695
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000696 In addition, the replacements using :func:`check_output` will fail with a
697 :exc:`CalledProcessError` if the requested operation produces a non-zero
Serhiy Storchakac8f26f52013-08-24 00:28:38 +0300698 return code. The output is still available as the
699 :attr:`~CalledProcessError.output` attribute of the raised exception.
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000700
701In the following examples, we assume that the relevant functions have already
Ezio Melotti26025d62012-11-08 10:07:10 +0200702been imported from the :mod:`subprocess` module.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000703
704
705Replacing /bin/sh shell backquote
706^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
707
708::
709
710 output=`mycmd myarg`
Nick Coghlan86711572011-10-24 22:19:40 +1000711 # becomes
712 output = check_output(["mycmd", "myarg"])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000713
714
Benjamin Petersoncae58482008-10-10 20:38:49 +0000715Replacing shell pipeline
716^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +0000717
718::
719
720 output=`dmesg | grep hda`
Nick Coghlan86711572011-10-24 22:19:40 +1000721 # becomes
Georg Brandl8ec7f652007-08-15 14:28:01 +0000722 p1 = Popen(["dmesg"], stdout=PIPE)
723 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Gregory P. Smithe3e967f2011-02-05 21:49:56 +0000724 p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000725 output = p2.communicate()[0]
726
Gregory P. Smithe3e967f2011-02-05 21:49:56 +0000727The p1.stdout.close() call after starting the p2 is important in order for p1
728to receive a SIGPIPE if p2 exits before p1.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000729
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000730Alternatively, for trusted input, the shell's own pipeline support may still
R David Murray5fc56eb2012-04-03 08:46:05 -0400731be used directly::
Nick Coghlan86711572011-10-24 22:19:40 +1000732
733 output=`dmesg | grep hda`
734 # becomes
735 output=check_output("dmesg | grep hda", shell=True)
736
737
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000738Replacing :func:`os.system`
739^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +0000740
741::
742
743 sts = os.system("mycmd" + " myarg")
Nick Coghlan86711572011-10-24 22:19:40 +1000744 # becomes
745 sts = call("mycmd" + " myarg", shell=True)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000746
747Notes:
748
749* Calling the program through the shell is usually not required.
750
Georg Brandl8ec7f652007-08-15 14:28:01 +0000751A more realistic example would look like this::
752
753 try:
754 retcode = call("mycmd" + " myarg", shell=True)
755 if retcode < 0:
756 print >>sys.stderr, "Child was terminated by signal", -retcode
757 else:
758 print >>sys.stderr, "Child returned", retcode
Ezio Melottie793f442012-10-26 23:10:07 +0300759 except OSError as e:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000760 print >>sys.stderr, "Execution failed:", e
761
762
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000763Replacing the :func:`os.spawn <os.spawnl>` family
764^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +0000765
766P_NOWAIT example::
767
768 pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
769 ==>
770 pid = Popen(["/bin/mycmd", "myarg"]).pid
771
772P_WAIT example::
773
774 retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
775 ==>
776 retcode = call(["/bin/mycmd", "myarg"])
777
778Vector example::
779
780 os.spawnvp(os.P_NOWAIT, path, args)
781 ==>
782 Popen([path] + args[1:])
783
784Environment example::
785
786 os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
787 ==>
788 Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
789
790
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000791Replacing :func:`os.popen`, :func:`os.popen2`, :func:`os.popen3`
792^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +0000793
794::
795
Philip Jenvey8b902042009-09-29 19:10:15 +0000796 pipe = os.popen("cmd", 'r', bufsize)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000797 ==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000798 pipe = Popen("cmd", shell=True, bufsize=bufsize, stdout=PIPE).stdout
Georg Brandl8ec7f652007-08-15 14:28:01 +0000799
800::
801
Philip Jenvey8b902042009-09-29 19:10:15 +0000802 pipe = os.popen("cmd", 'w', bufsize)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000803 ==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000804 pipe = Popen("cmd", shell=True, bufsize=bufsize, stdin=PIPE).stdin
Georg Brandl8ec7f652007-08-15 14:28:01 +0000805
806::
807
Philip Jenvey8b902042009-09-29 19:10:15 +0000808 (child_stdin, child_stdout) = os.popen2("cmd", mode, bufsize)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000809 ==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000810 p = Popen("cmd", shell=True, bufsize=bufsize,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000811 stdin=PIPE, stdout=PIPE, close_fds=True)
812 (child_stdin, child_stdout) = (p.stdin, p.stdout)
813
814::
815
816 (child_stdin,
817 child_stdout,
Philip Jenvey8b902042009-09-29 19:10:15 +0000818 child_stderr) = os.popen3("cmd", mode, bufsize)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000819 ==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000820 p = Popen("cmd", shell=True, bufsize=bufsize,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000821 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
822 (child_stdin,
823 child_stdout,
824 child_stderr) = (p.stdin, p.stdout, p.stderr)
825
826::
827
Philip Jenvey8b902042009-09-29 19:10:15 +0000828 (child_stdin, child_stdout_and_stderr) = os.popen4("cmd", mode,
829 bufsize)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000830 ==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000831 p = Popen("cmd", shell=True, bufsize=bufsize,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000832 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
833 (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
834
Philip Jenvey8b902042009-09-29 19:10:15 +0000835On Unix, os.popen2, os.popen3 and os.popen4 also accept a sequence as
836the command to execute, in which case arguments will be passed
837directly to the program without shell intervention. This usage can be
838replaced as follows::
839
840 (child_stdin, child_stdout) = os.popen2(["/bin/ls", "-l"], mode,
841 bufsize)
842 ==>
843 p = Popen(["/bin/ls", "-l"], bufsize=bufsize, stdin=PIPE, stdout=PIPE)
844 (child_stdin, child_stdout) = (p.stdin, p.stdout)
845
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000846Return code handling translates as follows::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000847
Philip Jenvey8b902042009-09-29 19:10:15 +0000848 pipe = os.popen("cmd", 'w')
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000849 ...
850 rc = pipe.close()
Stefan Kraha253dc12010-07-14 10:06:07 +0000851 if rc is not None and rc >> 8:
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000852 print "There were some errors"
853 ==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000854 process = Popen("cmd", 'w', shell=True, stdin=PIPE)
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000855 ...
856 process.stdin.close()
857 if process.wait() != 0:
858 print "There were some errors"
859
860
861Replacing functions from the :mod:`popen2` module
862^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +0000863
Georg Brandl8ec7f652007-08-15 14:28:01 +0000864::
865
866 (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
867 ==>
868 p = Popen(["somestring"], shell=True, bufsize=bufsize,
869 stdin=PIPE, stdout=PIPE, close_fds=True)
870 (child_stdout, child_stdin) = (p.stdout, p.stdin)
871
Philip Jenvey8b902042009-09-29 19:10:15 +0000872On Unix, popen2 also accepts a sequence as the command to execute, in
873which case arguments will be passed directly to the program without
874shell intervention. This usage can be replaced as follows::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000875
Philip Jenvey8b902042009-09-29 19:10:15 +0000876 (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize,
877 mode)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000878 ==>
879 p = Popen(["mycmd", "myarg"], bufsize=bufsize,
880 stdin=PIPE, stdout=PIPE, close_fds=True)
881 (child_stdout, child_stdin) = (p.stdout, p.stdin)
882
Georg Brandlf5d5a662008-12-06 11:57:12 +0000883:class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as
884:class:`subprocess.Popen`, except that:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000885
Georg Brandlf5d5a662008-12-06 11:57:12 +0000886* :class:`Popen` raises an exception if the execution fails.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000887
888* the *capturestderr* argument is replaced with the *stderr* argument.
889
Georg Brandlf5d5a662008-12-06 11:57:12 +0000890* ``stdin=PIPE`` and ``stdout=PIPE`` must be specified.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000891
892* popen2 closes all file descriptors by default, but you have to specify
Georg Brandlf5d5a662008-12-06 11:57:12 +0000893 ``close_fds=True`` with :class:`Popen`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000894
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000895
Eli Bendersky929e2762011-04-15 07:35:06 +0300896Notes
897-----
898
899.. _converting-argument-sequence:
900
901Converting an argument sequence to a string on Windows
902^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
903
904On Windows, an *args* sequence is converted to a string that can be parsed
905using the following rules (which correspond to the rules used by the MS C
906runtime):
907
9081. Arguments are delimited by white space, which is either a
909 space or a tab.
910
9112. A string surrounded by double quotation marks is
912 interpreted as a single argument, regardless of white space
913 contained within. A quoted string can be embedded in an
914 argument.
915
9163. A double quotation mark preceded by a backslash is
917 interpreted as a literal double quotation mark.
918
9194. Backslashes are interpreted literally, unless they
920 immediately precede a double quotation mark.
921
9225. If backslashes immediately precede a double quotation mark,
923 every pair of backslashes is interpreted as a literal
924 backslash. If the number of backslashes is odd, the last
925 backslash escapes the next double quotation mark as
926 described in rule 3.
927