blob: 114907f583689afe0466d83e9f3042b087012c52 [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
Benjamin Peterson944996f2014-03-12 21:41:35 -050015replace several older modules and functions::
Georg Brandl8ec7f652007-08-15 14:28:01 +000016
17 os.system
18 os.spawn*
19 os.popen*
20 popen2.*
21 commands.*
22
Gregory P. Smith8f813fe2014-04-15 07:59:44 -070023Information about how this module can be used to replace the older
24functions can be found in the subprocess-replacements_ section.
Georg Brandl8ec7f652007-08-15 14:28:01 +000025
Georg Brandl68b4e742008-07-01 19:59:00 +000026.. seealso::
27
Gregory P. Smith8f813fe2014-04-15 07:59:44 -070028 POSIX users (Linux, BSD, etc.) are strongly encouraged to install
29 and use the much more recent subprocess32_ module instead of the
30 version included with python 2.7. It is a drop in replacement with
31 better behavior in many situations.
32
Georg Brandl68b4e742008-07-01 19:59:00 +000033 :pep:`324` -- PEP proposing the subprocess module
34
Gregory P. Smith49bf4ce2014-04-15 08:01:27 -070035.. _subprocess32: https://pypi.python.org/pypi/subprocess32/
Georg Brandl8ec7f652007-08-15 14:28:01 +000036
Ezio Melotti26025d62012-11-08 10:07:10 +020037Using the :mod:`subprocess` Module
38----------------------------------
Georg Brandl8ec7f652007-08-15 14:28:01 +000039
Gregory P. Smith8f813fe2014-04-15 07:59:44 -070040The recommended way to launch subprocesses is to use the following
41convenience functions. For more advanced use cases when these do not
42meet your needs, use the underlying :class:`Popen` interface.
Nick Coghlan86711572011-10-24 22:19:40 +100043
44
Nick Coghlan2ed203a2011-10-26 21:05:56 +100045.. function:: call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
Nick Coghlan86711572011-10-24 22:19:40 +100046
47 Run the command described by *args*. Wait for command to complete, then
48 return the :attr:`returncode` attribute.
49
50 The arguments shown above are merely the most common ones, described below
Nick Coghlan87ba6422011-10-27 17:55:13 +100051 in :ref:`frequently-used-arguments` (hence the slightly odd notation in
52 the abbreviated signature). The full function signature is the same as
53 that of the :class:`Popen` constructor - this functions passes all
54 supplied arguments directly through to that interface.
Nick Coghlan86711572011-10-24 22:19:40 +100055
56 Examples::
57
58 >>> subprocess.call(["ls", "-l"])
59 0
60
Nick Coghlan2ed203a2011-10-26 21:05:56 +100061 >>> subprocess.call("exit 1", shell=True)
Nick Coghlan86711572011-10-24 22:19:40 +100062 1
63
64 .. warning::
65
Gregory P. Smith8f813fe2014-04-15 07:59:44 -070066 Using ``shell=True`` can be a security hazard. See the warning
67 under :ref:`frequently-used-arguments` for details.
Nick Coghlan87ba6422011-10-27 17:55:13 +100068
69 .. note::
70
Gregory P. Smith8f813fe2014-04-15 07:59:44 -070071 Do not use ``stdout=PIPE`` or ``stderr=PIPE`` with this function
72 as that can deadlock based on the child process output volume.
73 Use :class:`Popen` with the :meth:`communicate` method when you
74 need pipes.
Nick Coghlan86711572011-10-24 22:19:40 +100075
76
Nick Coghlan87ba6422011-10-27 17:55:13 +100077.. function:: check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
Nick Coghlan86711572011-10-24 22:19:40 +100078
79 Run command with arguments. Wait for command to complete. If the return
80 code was zero then return, otherwise raise :exc:`CalledProcessError`. The
81 :exc:`CalledProcessError` object will have the return code in the
Serhiy Storchakac8f26f52013-08-24 00:28:38 +030082 :attr:`~CalledProcessError.returncode` attribute.
Nick Coghlan86711572011-10-24 22:19:40 +100083
Nick Coghlan87ba6422011-10-27 17:55:13 +100084 The arguments shown above are merely the most common ones, described below
85 in :ref:`frequently-used-arguments` (hence the slightly odd notation in
86 the abbreviated signature). The full function signature is the same as
87 that of the :class:`Popen` constructor - this functions passes all
88 supplied arguments directly through to that interface.
89
90 Examples::
Nick Coghlan86711572011-10-24 22:19:40 +100091
92 >>> subprocess.check_call(["ls", "-l"])
93 0
94
Nick Coghlan2ed203a2011-10-26 21:05:56 +100095 >>> subprocess.check_call("exit 1", shell=True)
Nick Coghlan86711572011-10-24 22:19:40 +100096 Traceback (most recent call last):
97 ...
Nick Coghlan2ed203a2011-10-26 21:05:56 +100098 subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
Nick Coghlan86711572011-10-24 22:19:40 +100099
100 .. versionadded:: 2.5
101
102 .. warning::
103
Gregory P. Smith8f813fe2014-04-15 07:59:44 -0700104 Using ``shell=True`` can be a security hazard. See the warning
105 under :ref:`frequently-used-arguments` for details.
Nick Coghlan87ba6422011-10-27 17:55:13 +1000106
107 .. note::
108
Gregory P. Smith8f813fe2014-04-15 07:59:44 -0700109 Do not use ``stdout=PIPE`` or ``stderr=PIPE`` with this function
110 as that can deadlock based on the child process output volume.
111 Use :class:`Popen` with the :meth:`communicate` method when you
112 need pipes.
Nick Coghlan86711572011-10-24 22:19:40 +1000113
114
Nick Coghlan87ba6422011-10-27 17:55:13 +1000115.. function:: check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
Nick Coghlan86711572011-10-24 22:19:40 +1000116
117 Run command with arguments and return its output as a byte string.
118
119 If the return code was non-zero it raises a :exc:`CalledProcessError`. The
120 :exc:`CalledProcessError` object will have the return code in the
Serhiy Storchakac8f26f52013-08-24 00:28:38 +0300121 :attr:`~CalledProcessError.returncode` attribute and any output in the
122 :attr:`~CalledProcessError.output` attribute.
Nick Coghlan86711572011-10-24 22:19:40 +1000123
Nick Coghlan87ba6422011-10-27 17:55:13 +1000124 The arguments shown above are merely the most common ones, described below
125 in :ref:`frequently-used-arguments` (hence the slightly odd notation in
126 the abbreviated signature). The full function signature is largely the
127 same as that of the :class:`Popen` constructor, except that *stdout* is
128 not permitted as it is used internally. All other supplied arguments are
129 passed directly through to the :class:`Popen` constructor.
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000130
Nick Coghlan86711572011-10-24 22:19:40 +1000131 Examples::
132
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000133 >>> subprocess.check_output(["echo", "Hello World!"])
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000134 'Hello World!\n'
135
136 >>> subprocess.check_output("exit 1", shell=True)
Nick Coghlan86711572011-10-24 22:19:40 +1000137 Traceback (most recent call last):
138 ...
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000139 subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
Nick Coghlan86711572011-10-24 22:19:40 +1000140
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000141 To also capture standard error in the result, use
142 ``stderr=subprocess.STDOUT``::
Nick Coghlan86711572011-10-24 22:19:40 +1000143
144 >>> subprocess.check_output(
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000145 ... "ls non_existent_file; exit 0",
146 ... stderr=subprocess.STDOUT,
147 ... shell=True)
Nick Coghlan86711572011-10-24 22:19:40 +1000148 'ls: non_existent_file: No such file or directory\n'
149
150 .. versionadded:: 2.7
151
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000152 .. warning::
153
Gregory P. Smith8f813fe2014-04-15 07:59:44 -0700154 Using ``shell=True`` can be a security hazard. See the warning
155 under :ref:`frequently-used-arguments` for details.
Nick Coghlan87ba6422011-10-27 17:55:13 +1000156
157 .. note::
158
Gregory P. Smith8f813fe2014-04-15 07:59:44 -0700159 Do not use ``stderr=PIPE`` with this function as that can deadlock
160 based on the child process error volume. Use :class:`Popen` with
161 the :meth:`communicate` method when you need a stderr pipe.
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000162
Nick Coghlan86711572011-10-24 22:19:40 +1000163
164.. data:: PIPE
165
166 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
167 to :class:`Popen` and indicates that a pipe to the standard stream should be
168 opened.
169
170
171.. data:: STDOUT
172
173 Special value that can be used as the *stderr* argument to :class:`Popen` and
174 indicates that standard error should go into the same handle as standard
175 output.
176
177
Andrew Svetlov8afcec42012-08-09 15:23:49 +0300178.. exception:: CalledProcessError
179
180 Exception raised when a process run by :func:`check_call` or
181 :func:`check_output` returns a non-zero exit status.
182
183 .. attribute:: returncode
184
185 Exit status of the child process.
186
187 .. attribute:: cmd
188
189 Command that was used to spawn the child process.
190
191 .. attribute:: output
192
193 Output of the child process if this exception is raised by
194 :func:`check_output`. Otherwise, ``None``.
195
196
197
Nick Coghlan86711572011-10-24 22:19:40 +1000198.. _frequently-used-arguments:
199
200Frequently Used Arguments
201^^^^^^^^^^^^^^^^^^^^^^^^^
202
203To support a wide variety of use cases, the :class:`Popen` constructor (and
204the convenience functions) accept a large number of optional arguments. For
205most typical use cases, many of these arguments can be safely left at their
206default values. The arguments that are most commonly needed are:
207
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000208 *args* is required for all calls and should be a string, or a sequence of
209 program arguments. Providing a sequence of arguments is generally
210 preferred, as it allows the module to take care of any required escaping
211 and quoting of arguments (e.g. to permit spaces in file names). If passing
212 a single string, either *shell* must be :const:`True` (see below) or else
213 the string must simply name the program to be executed without specifying
214 any arguments.
Nick Coghlan86711572011-10-24 22:19:40 +1000215
216 *stdin*, *stdout* and *stderr* specify the executed program's standard input,
217 standard output and standard error file handles, respectively. Valid values
218 are :data:`PIPE`, an existing file descriptor (a positive integer), an
219 existing file object, and ``None``. :data:`PIPE` indicates that a new pipe
220 to the child should be created. With the default settings of ``None``, no
221 redirection will occur; the child's file handles will be inherited from the
222 parent. Additionally, *stderr* can be :data:`STDOUT`, which indicates that
223 the stderr data from the child process should be captured into the same file
224 handle as for stdout.
225
R David Murray5618aaa2012-08-15 11:15:39 -0400226 .. index::
227 single: universal newlines; subprocess module
228
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000229 When *stdout* or *stderr* are pipes and *universal_newlines* is
R David Murray5618aaa2012-08-15 11:15:39 -0400230 ``True`` then all line endings will be converted to ``'\n'`` as described
Ezio Melotti93324d72013-03-28 05:47:31 +0200231 for the :term:`universal newlines` ``'U'`` mode argument to :func:`open`.
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000232
Ezio Melottieab4df52012-09-15 08:33:12 +0300233 If *shell* is ``True``, the specified command will be executed through
234 the shell. This can be useful if you are using Python primarily for the
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000235 enhanced control flow it offers over most system shells and still want
Ezio Melottieab4df52012-09-15 08:33:12 +0300236 convenient access to other shell features such as shell pipes, filename
237 wildcards, environment variable expansion, and expansion of ``~`` to a
238 user's home directory. However, note that Python itself offers
239 implementations of many shell-like features (in particular, :mod:`glob`,
240 :mod:`fnmatch`, :func:`os.walk`, :func:`os.path.expandvars`,
241 :func:`os.path.expanduser`, and :mod:`shutil`).
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000242
243 .. warning::
244
245 Executing shell commands that incorporate unsanitized input from an
246 untrusted source makes a program vulnerable to `shell injection
247 <http://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_,
248 a serious security flaw which can result in arbitrary command execution.
Chris Jerdonek1e651592012-10-10 22:58:57 -0700249 For this reason, the use of ``shell=True`` is **strongly discouraged**
250 in cases where the command string is constructed from external input::
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000251
252 >>> from subprocess import call
253 >>> filename = input("What file would you like to display?\n")
254 What file would you like to display?
255 non_existent; rm -rf / #
256 >>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...
257
258 ``shell=False`` disables all shell based features, but does not suffer
259 from this vulnerability; see the Note in the :class:`Popen` constructor
260 documentation for helpful hints in getting ``shell=False`` to work.
261
Andrew Svetlov61822662012-10-28 11:48:02 +0200262 When using ``shell=True``, :func:`pipes.quote` can be used to properly
263 escape whitespace and shell metacharacters in strings that are going to
264 be used to construct shell commands.
265
Nick Coghlan86711572011-10-24 22:19:40 +1000266These options, along with all of the other options, are described in more
267detail in the :class:`Popen` constructor documentation.
268
269
Sandro Tosidbcbd102011-12-25 11:27:22 +0100270Popen Constructor
Sandro Tosi44585bd2011-12-25 17:13:10 +0100271^^^^^^^^^^^^^^^^^
Nick Coghlan86711572011-10-24 22:19:40 +1000272
273The underlying process creation and management in this module is handled by
274the :class:`Popen` class. It offers a lot of flexibility so that developers
275are able to handle the less common cases not covered by the convenience
276functions.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000277
278
Chris Jerdonek2a6672b2012-10-10 17:55:41 -0700279.. class:: Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, \
280 stderr=None, preexec_fn=None, close_fds=False, shell=False, \
281 cwd=None, env=None, universal_newlines=False, \
282 startupinfo=None, creationflags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000283
Chris Jerdonek2a6672b2012-10-10 17:55:41 -0700284 Execute a child program in a new process. On Unix, the class uses
285 :meth:`os.execvp`-like behavior to execute the child program. On Windows,
286 the class uses the Windows ``CreateProcess()`` function. The arguments to
287 :class:`Popen` are as follows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000288
Chris Jerdonek1906c0c2012-10-08 23:18:17 -0700289 *args* should be a sequence of program arguments or else a single string.
290 By default, the program to execute is the first item in *args* if *args* is
Chris Jerdonek2a6672b2012-10-10 17:55:41 -0700291 a sequence. If *args* is a string, the interpretation is
292 platform-dependent and described below. See the *shell* and *executable*
293 arguments for additional differences from the default behavior. Unless
294 otherwise stated, it is recommended to pass *args* as a sequence.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000295
Chris Jerdonek2a6672b2012-10-10 17:55:41 -0700296 On Unix, if *args* is a string, the string is interpreted as the name or
297 path of the program to execute. However, this can only be done if not
298 passing arguments to the program.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000299
Nick Coghlan7dfc9e12010-02-04 12:43:58 +0000300 .. note::
301
302 :meth:`shlex.split` can be useful when determining the correct
303 tokenization for *args*, especially in complex cases::
304
305 >>> import shlex, subprocess
306 >>> command_line = raw_input()
307 /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
308 >>> args = shlex.split(command_line)
309 >>> print args
310 ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
311 >>> p = subprocess.Popen(args) # Success!
312
313 Note in particular that options (such as *-input*) and arguments (such
314 as *eggs.txt*) that are separated by whitespace in the shell go in separate
315 list elements, while arguments that need quoting or backslash escaping when
316 used in the shell (such as filenames containing spaces or the *echo* command
317 shown above) are single list elements.
318
Chris Jerdonek2a6672b2012-10-10 17:55:41 -0700319 On Windows, if *args* is a sequence, it will be converted to a string in a
320 manner described in :ref:`converting-argument-sequence`. This is because
321 the underlying ``CreateProcess()`` operates on strings.
Chris Jerdonek1906c0c2012-10-08 23:18:17 -0700322
323 The *shell* argument (which defaults to *False*) specifies whether to use
Chris Jerdonek2a6672b2012-10-10 17:55:41 -0700324 the shell as the program to execute. If *shell* is *True*, it is
325 recommended to pass *args* as a string rather than as a sequence.
Chris Jerdonek1906c0c2012-10-08 23:18:17 -0700326
327 On Unix with ``shell=True``, the shell defaults to :file:`/bin/sh`. If
328 *args* is a string, the string specifies the command
329 to execute through the shell. This means that the string must be
Nick Coghlan7dfc9e12010-02-04 12:43:58 +0000330 formatted exactly as it would be when typed at the shell prompt. This
331 includes, for example, quoting or backslash escaping filenames with spaces in
332 them. If *args* is a sequence, the first item specifies the command string, and
333 any additional items will be treated as additional arguments to the shell
Chris Jerdonek1906c0c2012-10-08 23:18:17 -0700334 itself. That is to say, :class:`Popen` does the equivalent of::
Nick Coghlan7dfc9e12010-02-04 12:43:58 +0000335
336 Popen(['/bin/sh', '-c', args[0], args[1], ...])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000337
Chris Jerdonek1906c0c2012-10-08 23:18:17 -0700338 On Windows with ``shell=True``, the :envvar:`COMSPEC` environment variable
339 specifies the default shell. The only time you need to specify
340 ``shell=True`` on Windows is when the command you wish to execute is built
341 into the shell (e.g. :command:`dir` or :command:`copy`). You do not need
342 ``shell=True`` to run a batch file or console-based executable.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000343
Chris Jerdonek1e651592012-10-10 22:58:57 -0700344 .. warning::
345
346 Passing ``shell=True`` can be a security hazard if combined with
347 untrusted input. See the warning under :ref:`frequently-used-arguments`
348 for details.
349
Georg Brandl8ec7f652007-08-15 14:28:01 +0000350 *bufsize*, if given, has the same meaning as the corresponding argument to the
351 built-in open() function: :const:`0` means unbuffered, :const:`1` means line
352 buffered, any other positive value means use a buffer of (approximately) that
353 size. A negative *bufsize* means to use the system default, which usually means
354 fully buffered. The default value for *bufsize* is :const:`0` (unbuffered).
355
Antoine Pitrouc3955452010-06-02 17:08:47 +0000356 .. note::
357
358 If you experience performance issues, it is recommended that you try to
359 enable buffering by setting *bufsize* to either -1 or a large enough
360 positive value (such as 4096).
361
Chris Jerdonek1906c0c2012-10-08 23:18:17 -0700362 The *executable* argument specifies a replacement program to execute. It
363 is very seldom needed. When ``shell=False``, *executable* replaces the
Chris Jerdonek2a6672b2012-10-10 17:55:41 -0700364 program to execute specified by *args*. However, the original *args* is
365 still passed to the program. Most programs treat the program specified
366 by *args* as the command name, which can then be different from the program
367 actually executed. On Unix, the *args* name
Chris Jerdonek1906c0c2012-10-08 23:18:17 -0700368 becomes the display name for the executable in utilities such as
369 :program:`ps`. If ``shell=True``, on Unix the *executable* argument
370 specifies a replacement shell for the default :file:`/bin/sh`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000371
Nick Coghlan86711572011-10-24 22:19:40 +1000372 *stdin*, *stdout* and *stderr* specify the executed program's standard input,
Georg Brandlf5d5a662008-12-06 11:57:12 +0000373 standard output and standard error file handles, respectively. Valid values
374 are :data:`PIPE`, an existing file descriptor (a positive integer), an
375 existing file object, and ``None``. :data:`PIPE` indicates that a new pipe
Nick Coghlan86711572011-10-24 22:19:40 +1000376 to the child should be created. With the default settings of ``None``, no
377 redirection will occur; the child's file handles will be inherited from the
378 parent. Additionally, *stderr* can be :data:`STDOUT`, which indicates that
379 the stderr data from the child process should be captured into the same file
380 handle as for stdout.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000381
382 If *preexec_fn* is set to a callable object, this object will be called in the
383 child process just before the child is executed. (Unix only)
384
385 If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and
386 :const:`2` will be closed before the child process is executed. (Unix only).
387 Or, on Windows, if *close_fds* is true then no handles will be inherited by the
388 child process. Note that on Windows, you cannot set *close_fds* to true and
389 also redirect the standard handles by setting *stdin*, *stdout* or *stderr*.
390
Georg Brandl8ec7f652007-08-15 14:28:01 +0000391 If *cwd* is not ``None``, the child's current directory will be changed to *cwd*
392 before it is executed. Note that this directory is not considered when
393 searching the executable, so you can't specify the program's path relative to
394 *cwd*.
395
Georg Brandlf801b0f2008-04-19 16:58:49 +0000396 If *env* is not ``None``, it must be a mapping that defines the environment
397 variables for the new process; these are used instead of inheriting the current
398 process' environment, which is the default behavior.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000399
R. David Murray72030812009-04-16 18:12:53 +0000400 .. note::
R. David Murray6076d392009-04-15 22:33:07 +0000401
R. David Murray72030812009-04-16 18:12:53 +0000402 If specified, *env* must provide any variables required
403 for the program to execute. On Windows, in order to run a
404 `side-by-side assembly`_ the specified *env* **must** include a valid
R. David Murray6076d392009-04-15 22:33:07 +0000405 :envvar:`SystemRoot`.
406
R. David Murray72030812009-04-16 18:12:53 +0000407 .. _side-by-side assembly: http://en.wikipedia.org/wiki/Side-by-Side_Assembly
408
R David Murrayc7b8f802012-08-15 11:22:58 -0400409 If *universal_newlines* is ``True``, the file objects *stdout* and *stderr*
410 are opened as text files in :term:`universal newlines` mode. Lines may be
411 terminated by any of ``'\n'``, the Unix end-of-line convention, ``'\r'``,
412 the old Macintosh convention or ``'\r\n'``, the Windows convention. All of
413 these external representations are seen as ``'\n'`` by the Python program.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000414
415 .. note::
416
Georg Brandl6ab5d082009-12-20 14:33:20 +0000417 This feature is only available if Python is built with universal newline
418 support (the default). Also, the newlines attribute of the file objects
419 :attr:`stdout`, :attr:`stdin` and :attr:`stderr` are not updated by the
420 communicate() method.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000421
Brian Curtinbb23bd62011-04-29 22:23:46 -0500422 If given, *startupinfo* will be a :class:`STARTUPINFO` object, which is
423 passed to the underlying ``CreateProcess`` function.
424 *creationflags*, if given, can be :data:`CREATE_NEW_CONSOLE` or
425 :data:`CREATE_NEW_PROCESS_GROUP`. (Windows only)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000426
427
Georg Brandl8ec7f652007-08-15 14:28:01 +0000428Exceptions
429^^^^^^^^^^
430
431Exceptions raised in the child process, before the new program has started to
432execute, will be re-raised in the parent. Additionally, the exception object
433will have one extra attribute called :attr:`child_traceback`, which is a string
Georg Brandl21946af2010-10-06 09:28:45 +0000434containing traceback information from the child's point of view.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000435
436The most common exception raised is :exc:`OSError`. This occurs, for example,
437when trying to execute a non-existent file. Applications should prepare for
438:exc:`OSError` exceptions.
439
440A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid
441arguments.
442
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000443:func:`check_call` and :func:`check_output` will raise
444:exc:`CalledProcessError` if the called process returns a non-zero return
445code.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000446
447
448Security
449^^^^^^^^
450
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000451Unlike some other popen functions, this implementation will never call a
452system shell implicitly. This means that all characters, including shell
453metacharacters, can safely be passed to child processes. Obviously, if the
454shell is invoked explicitly, then it is the application's responsibility to
Nick Coghlan63c54e82011-10-26 21:34:26 +1000455ensure that all whitespace and metacharacters are quoted appropriately.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000456
457
458Popen Objects
459-------------
460
461Instances of the :class:`Popen` class have the following methods:
462
463
464.. method:: Popen.poll()
465
Serhiy Storchakac8f26f52013-08-24 00:28:38 +0300466 Check if child process has terminated. Set and return
467 :attr:`~Popen.returncode` attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000468
469
470.. method:: Popen.wait()
471
Serhiy Storchakac8f26f52013-08-24 00:28:38 +0300472 Wait for child process to terminate. Set and return
473 :attr:`~Popen.returncode` attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000474
Georg Brandl143de622008-08-04 06:29:36 +0000475 .. warning::
476
Philip Jenvey26275532009-12-03 02:25:54 +0000477 This will deadlock when using ``stdout=PIPE`` and/or
478 ``stderr=PIPE`` and the child process generates enough output to
479 a pipe such that it blocks waiting for the OS pipe buffer to
480 accept more data. Use :meth:`communicate` to avoid that.
Gregory P. Smith08792502008-08-04 01:03:50 +0000481
Georg Brandl8ec7f652007-08-15 14:28:01 +0000482
483.. method:: Popen.communicate(input=None)
484
485 Interact with process: Send data to stdin. Read data from stdout and stderr,
486 until end-of-file is reached. Wait for process to terminate. The optional
487 *input* argument should be a string to be sent to the child process, or
488 ``None``, if no data should be sent to the child.
489
Georg Brandl17432012008-12-04 21:28:16 +0000490 :meth:`communicate` returns a tuple ``(stdoutdata, stderrdata)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000491
Georg Brandl439f2502007-11-24 11:31:46 +0000492 Note that if you want to send data to the process's stdin, you need to create
493 the Popen object with ``stdin=PIPE``. Similarly, to get anything other than
494 ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or
495 ``stderr=PIPE`` too.
496
Georg Brandl2cb103f2008-01-06 16:01:26 +0000497 .. note::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000498
Georg Brandl2cb103f2008-01-06 16:01:26 +0000499 The data read is buffered in memory, so do not use this method if the data
500 size is large or unlimited.
501
Georg Brandl8ec7f652007-08-15 14:28:01 +0000502
Christian Heimese74c8f22008-04-19 02:23:57 +0000503.. method:: Popen.send_signal(signal)
504
505 Sends the signal *signal* to the child.
506
507 .. note::
508
Brian Curtine5aa8862010-04-02 23:26:06 +0000509 On Windows, SIGTERM is an alias for :meth:`terminate`. CTRL_C_EVENT and
Ezio Melotti9ccc5812010-04-05 08:16:41 +0000510 CTRL_BREAK_EVENT can be sent to processes started with a *creationflags*
Brian Curtine5aa8862010-04-02 23:26:06 +0000511 parameter which includes `CREATE_NEW_PROCESS_GROUP`.
Georg Brandl734de682008-04-19 08:23:59 +0000512
513 .. versionadded:: 2.6
Christian Heimese74c8f22008-04-19 02:23:57 +0000514
515
516.. method:: Popen.terminate()
517
518 Stop the child. On Posix OSs the method sends SIGTERM to the
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100519 child. On Windows the Win32 API function :c:func:`TerminateProcess` is called
Christian Heimese74c8f22008-04-19 02:23:57 +0000520 to stop the child.
521
Georg Brandl734de682008-04-19 08:23:59 +0000522 .. versionadded:: 2.6
523
Christian Heimese74c8f22008-04-19 02:23:57 +0000524
525.. method:: Popen.kill()
526
527 Kills the child. On Posix OSs the function sends SIGKILL to the child.
Georg Brandl734de682008-04-19 08:23:59 +0000528 On Windows :meth:`kill` is an alias for :meth:`terminate`.
529
530 .. versionadded:: 2.6
Christian Heimese74c8f22008-04-19 02:23:57 +0000531
532
Georg Brandl8ec7f652007-08-15 14:28:01 +0000533The following attributes are also available:
534
Georg Brandl143de622008-08-04 06:29:36 +0000535.. warning::
536
Ezio Melotti8662c842012-08-27 10:00:05 +0300537 Use :meth:`~Popen.communicate` rather than :attr:`.stdin.write <Popen.stdin>`,
538 :attr:`.stdout.read <Popen.stdout>` or :attr:`.stderr.read <Popen.stderr>` to avoid
Georg Brandl16a57f62009-04-27 15:29:09 +0000539 deadlocks due to any of the other OS pipe buffers filling up and blocking the
540 child process.
Georg Brandl143de622008-08-04 06:29:36 +0000541
542
Georg Brandl8ec7f652007-08-15 14:28:01 +0000543.. attribute:: Popen.stdin
544
Georg Brandlf5d5a662008-12-06 11:57:12 +0000545 If the *stdin* argument was :data:`PIPE`, this attribute is a file object
546 that provides input to the child process. Otherwise, it is ``None``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000547
548
549.. attribute:: Popen.stdout
550
Georg Brandlf5d5a662008-12-06 11:57:12 +0000551 If the *stdout* argument was :data:`PIPE`, this attribute is a file object
552 that provides output from the child process. Otherwise, it is ``None``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000553
554
555.. attribute:: Popen.stderr
556
Georg Brandlf5d5a662008-12-06 11:57:12 +0000557 If the *stderr* argument was :data:`PIPE`, this attribute is a file object
558 that provides error output from the child process. Otherwise, it is
559 ``None``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000560
561
562.. attribute:: Popen.pid
563
564 The process ID of the child process.
565
Georg Brandl0b56ce02010-03-21 09:28:16 +0000566 Note that if you set the *shell* argument to ``True``, this is the process ID
567 of the spawned shell.
568
Georg Brandl8ec7f652007-08-15 14:28:01 +0000569
570.. attribute:: Popen.returncode
571
Georg Brandl2cb103f2008-01-06 16:01:26 +0000572 The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly
573 by :meth:`communicate`). A ``None`` value indicates that the process
574 hasn't terminated yet.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000575
Georg Brandl2cb103f2008-01-06 16:01:26 +0000576 A negative value ``-N`` indicates that the child was terminated by signal
577 ``N`` (Unix only).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000578
579
Brian Curtinbb23bd62011-04-29 22:23:46 -0500580Windows Popen Helpers
581---------------------
582
583The :class:`STARTUPINFO` class and following constants are only available
584on Windows.
585
586.. class:: STARTUPINFO()
587
588 Partial support of the Windows
589 `STARTUPINFO <http://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx>`__
590 structure is used for :class:`Popen` creation.
591
592 .. attribute:: dwFlags
593
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700594 A bit field that determines whether certain :class:`STARTUPINFO`
595 attributes are used when the process creates a window. ::
Brian Curtinbb23bd62011-04-29 22:23:46 -0500596
597 si = subprocess.STARTUPINFO()
598 si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
599
600 .. attribute:: hStdInput
601
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700602 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
603 is the standard input handle for the process. If
604 :data:`STARTF_USESTDHANDLES` is not specified, the default for standard
605 input is the keyboard buffer.
Brian Curtinbb23bd62011-04-29 22:23:46 -0500606
607 .. attribute:: hStdOutput
608
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700609 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
610 is the standard output handle for the process. Otherwise, this attribute
611 is ignored and the default for standard output is the console window's
Brian Curtinbb23bd62011-04-29 22:23:46 -0500612 buffer.
613
614 .. attribute:: hStdError
615
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700616 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
617 is the standard error handle for the process. Otherwise, this attribute is
Brian Curtinbb23bd62011-04-29 22:23:46 -0500618 ignored and the default for standard error is the console window's buffer.
619
620 .. attribute:: wShowWindow
621
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700622 If :attr:`dwFlags` specifies :data:`STARTF_USESHOWWINDOW`, this attribute
Brian Curtinbb23bd62011-04-29 22:23:46 -0500623 can be any of the values that can be specified in the ``nCmdShow``
624 parameter for the
625 `ShowWindow <http://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx>`__
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700626 function, except for ``SW_SHOWDEFAULT``. Otherwise, this attribute is
Brian Curtinbb23bd62011-04-29 22:23:46 -0500627 ignored.
628
629 :data:`SW_HIDE` is provided for this attribute. It is used when
630 :class:`Popen` is called with ``shell=True``.
631
632
633Constants
634^^^^^^^^^
635
636The :mod:`subprocess` module exposes the following constants.
637
638.. data:: STD_INPUT_HANDLE
639
640 The standard input device. Initially, this is the console input buffer,
641 ``CONIN$``.
642
643.. data:: STD_OUTPUT_HANDLE
644
645 The standard output device. Initially, this is the active console screen
646 buffer, ``CONOUT$``.
647
648.. data:: STD_ERROR_HANDLE
649
650 The standard error device. Initially, this is the active console screen
651 buffer, ``CONOUT$``.
652
653.. data:: SW_HIDE
654
655 Hides the window. Another window will be activated.
656
657.. data:: STARTF_USESTDHANDLES
658
659 Specifies that the :attr:`STARTUPINFO.hStdInput`,
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700660 :attr:`STARTUPINFO.hStdOutput`, and :attr:`STARTUPINFO.hStdError` attributes
Brian Curtinbb23bd62011-04-29 22:23:46 -0500661 contain additional information.
662
663.. data:: STARTF_USESHOWWINDOW
664
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700665 Specifies that the :attr:`STARTUPINFO.wShowWindow` attribute contains
Brian Curtinbb23bd62011-04-29 22:23:46 -0500666 additional information.
667
668.. data:: CREATE_NEW_CONSOLE
669
670 The new process has a new console, instead of inheriting its parent's
671 console (the default).
672
673 This flag is always set when :class:`Popen` is created with ``shell=True``.
674
675.. data:: CREATE_NEW_PROCESS_GROUP
676
677 A :class:`Popen` ``creationflags`` parameter to specify that a new process
678 group will be created. This flag is necessary for using :func:`os.kill`
679 on the subprocess.
680
681 This flag is ignored if :data:`CREATE_NEW_CONSOLE` is specified.
682
683
Georg Brandl0ba92b22008-06-22 09:05:29 +0000684.. _subprocess-replacements:
685
Ezio Melotti26025d62012-11-08 10:07:10 +0200686Replacing Older Functions with the :mod:`subprocess` Module
687-----------------------------------------------------------
Georg Brandl8ec7f652007-08-15 14:28:01 +0000688
Nick Coghlan86711572011-10-24 22:19:40 +1000689In this section, "a becomes b" means that b can be used as a replacement for a.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000690
691.. note::
692
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000693 All "a" functions in this section fail (more or less) silently if the
694 executed program cannot be found; the "b" replacements raise :exc:`OSError`
695 instead.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000696
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000697 In addition, the replacements using :func:`check_output` will fail with a
698 :exc:`CalledProcessError` if the requested operation produces a non-zero
Serhiy Storchakac8f26f52013-08-24 00:28:38 +0300699 return code. The output is still available as the
700 :attr:`~CalledProcessError.output` attribute of the raised exception.
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000701
702In the following examples, we assume that the relevant functions have already
Ezio Melotti26025d62012-11-08 10:07:10 +0200703been imported from the :mod:`subprocess` module.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000704
705
706Replacing /bin/sh shell backquote
707^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
708
709::
710
711 output=`mycmd myarg`
Nick Coghlan86711572011-10-24 22:19:40 +1000712 # becomes
713 output = check_output(["mycmd", "myarg"])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000714
715
Benjamin Petersoncae58482008-10-10 20:38:49 +0000716Replacing shell pipeline
717^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +0000718
719::
720
721 output=`dmesg | grep hda`
Nick Coghlan86711572011-10-24 22:19:40 +1000722 # becomes
Georg Brandl8ec7f652007-08-15 14:28:01 +0000723 p1 = Popen(["dmesg"], stdout=PIPE)
724 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Gregory P. Smithe3e967f2011-02-05 21:49:56 +0000725 p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000726 output = p2.communicate()[0]
727
Gregory P. Smithe3e967f2011-02-05 21:49:56 +0000728The p1.stdout.close() call after starting the p2 is important in order for p1
729to receive a SIGPIPE if p2 exits before p1.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000730
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000731Alternatively, for trusted input, the shell's own pipeline support may still
R David Murray5fc56eb2012-04-03 08:46:05 -0400732be used directly::
Nick Coghlan86711572011-10-24 22:19:40 +1000733
734 output=`dmesg | grep hda`
735 # becomes
736 output=check_output("dmesg | grep hda", shell=True)
737
738
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000739Replacing :func:`os.system`
740^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +0000741
742::
743
Gregory P. Smith8f813fe2014-04-15 07:59:44 -0700744 status = os.system("mycmd" + " myarg")
Nick Coghlan86711572011-10-24 22:19:40 +1000745 # becomes
Gregory P. Smith8f813fe2014-04-15 07:59:44 -0700746 status = subprocess.call("mycmd" + " myarg", shell=True)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000747
748Notes:
749
750* Calling the program through the shell is usually not required.
751
Georg Brandl8ec7f652007-08-15 14:28:01 +0000752A more realistic example would look like this::
753
754 try:
755 retcode = call("mycmd" + " myarg", shell=True)
756 if retcode < 0:
757 print >>sys.stderr, "Child was terminated by signal", -retcode
758 else:
759 print >>sys.stderr, "Child returned", retcode
Ezio Melottie793f442012-10-26 23:10:07 +0300760 except OSError as e:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000761 print >>sys.stderr, "Execution failed:", e
762
763
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000764Replacing the :func:`os.spawn <os.spawnl>` family
765^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +0000766
767P_NOWAIT example::
768
769 pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
770 ==>
771 pid = Popen(["/bin/mycmd", "myarg"]).pid
772
773P_WAIT example::
774
775 retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
776 ==>
777 retcode = call(["/bin/mycmd", "myarg"])
778
779Vector example::
780
781 os.spawnvp(os.P_NOWAIT, path, args)
782 ==>
783 Popen([path] + args[1:])
784
785Environment example::
786
787 os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
788 ==>
789 Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
790
791
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000792Replacing :func:`os.popen`, :func:`os.popen2`, :func:`os.popen3`
793^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +0000794
795::
796
Philip Jenvey8b902042009-09-29 19:10:15 +0000797 pipe = os.popen("cmd", 'r', bufsize)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000798 ==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000799 pipe = Popen("cmd", shell=True, bufsize=bufsize, stdout=PIPE).stdout
Georg Brandl8ec7f652007-08-15 14:28:01 +0000800
801::
802
Philip Jenvey8b902042009-09-29 19:10:15 +0000803 pipe = os.popen("cmd", 'w', bufsize)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000804 ==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000805 pipe = Popen("cmd", shell=True, bufsize=bufsize, stdin=PIPE).stdin
Georg Brandl8ec7f652007-08-15 14:28:01 +0000806
807::
808
Philip Jenvey8b902042009-09-29 19:10:15 +0000809 (child_stdin, child_stdout) = os.popen2("cmd", mode, bufsize)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000810 ==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000811 p = Popen("cmd", shell=True, bufsize=bufsize,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000812 stdin=PIPE, stdout=PIPE, close_fds=True)
813 (child_stdin, child_stdout) = (p.stdin, p.stdout)
814
815::
816
817 (child_stdin,
818 child_stdout,
Philip Jenvey8b902042009-09-29 19:10:15 +0000819 child_stderr) = os.popen3("cmd", mode, bufsize)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000820 ==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000821 p = Popen("cmd", shell=True, bufsize=bufsize,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000822 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
823 (child_stdin,
824 child_stdout,
825 child_stderr) = (p.stdin, p.stdout, p.stderr)
826
827::
828
Philip Jenvey8b902042009-09-29 19:10:15 +0000829 (child_stdin, child_stdout_and_stderr) = os.popen4("cmd", mode,
830 bufsize)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000831 ==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000832 p = Popen("cmd", shell=True, bufsize=bufsize,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000833 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
834 (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
835
Philip Jenvey8b902042009-09-29 19:10:15 +0000836On Unix, os.popen2, os.popen3 and os.popen4 also accept a sequence as
837the command to execute, in which case arguments will be passed
838directly to the program without shell intervention. This usage can be
839replaced as follows::
840
841 (child_stdin, child_stdout) = os.popen2(["/bin/ls", "-l"], mode,
842 bufsize)
843 ==>
844 p = Popen(["/bin/ls", "-l"], bufsize=bufsize, stdin=PIPE, stdout=PIPE)
845 (child_stdin, child_stdout) = (p.stdin, p.stdout)
846
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000847Return code handling translates as follows::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000848
Philip Jenvey8b902042009-09-29 19:10:15 +0000849 pipe = os.popen("cmd", 'w')
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000850 ...
851 rc = pipe.close()
Stefan Kraha253dc12010-07-14 10:06:07 +0000852 if rc is not None and rc >> 8:
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000853 print "There were some errors"
854 ==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000855 process = Popen("cmd", 'w', shell=True, stdin=PIPE)
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000856 ...
857 process.stdin.close()
858 if process.wait() != 0:
859 print "There were some errors"
860
861
862Replacing functions from the :mod:`popen2` module
863^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +0000864
Georg Brandl8ec7f652007-08-15 14:28:01 +0000865::
866
867 (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
868 ==>
R David Murray0eb9ee92014-05-14 10:09:21 -0400869 p = Popen("somestring", shell=True, bufsize=bufsize,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000870 stdin=PIPE, stdout=PIPE, close_fds=True)
871 (child_stdout, child_stdin) = (p.stdout, p.stdin)
872
Philip Jenvey8b902042009-09-29 19:10:15 +0000873On Unix, popen2 also accepts a sequence as the command to execute, in
874which case arguments will be passed directly to the program without
875shell intervention. This usage can be replaced as follows::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000876
Philip Jenvey8b902042009-09-29 19:10:15 +0000877 (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize,
878 mode)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000879 ==>
880 p = Popen(["mycmd", "myarg"], bufsize=bufsize,
881 stdin=PIPE, stdout=PIPE, close_fds=True)
882 (child_stdout, child_stdin) = (p.stdout, p.stdin)
883
Georg Brandlf5d5a662008-12-06 11:57:12 +0000884:class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as
885:class:`subprocess.Popen`, except that:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000886
Georg Brandlf5d5a662008-12-06 11:57:12 +0000887* :class:`Popen` raises an exception if the execution fails.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000888
889* the *capturestderr* argument is replaced with the *stderr* argument.
890
Georg Brandlf5d5a662008-12-06 11:57:12 +0000891* ``stdin=PIPE`` and ``stdout=PIPE`` must be specified.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000892
893* popen2 closes all file descriptors by default, but you have to specify
Georg Brandlf5d5a662008-12-06 11:57:12 +0000894 ``close_fds=True`` with :class:`Popen`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000895
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000896
Eli Bendersky929e2762011-04-15 07:35:06 +0300897Notes
898-----
899
900.. _converting-argument-sequence:
901
902Converting an argument sequence to a string on Windows
903^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
904
905On Windows, an *args* sequence is converted to a string that can be parsed
906using the following rules (which correspond to the rules used by the MS C
907runtime):
908
9091. Arguments are delimited by white space, which is either a
910 space or a tab.
911
9122. A string surrounded by double quotation marks is
913 interpreted as a single argument, regardless of white space
914 contained within. A quoted string can be embedded in an
915 argument.
916
9173. A double quotation mark preceded by a backslash is
918 interpreted as a literal double quotation mark.
919
9204. Backslashes are interpreted literally, unless they
921 immediately precede a double quotation mark.
922
9235. If backslashes immediately precede a double quotation mark,
924 every pair of backslashes is interpreted as a literal
925 backslash. If the number of backslashes is odd, the last
926 backslash escapes the next double quotation mark as
927 described in rule 3.
928