blob: 380188427a3cabecf6c52aa117c07a8afbce4ac2 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2:mod:`subprocess` --- Subprocess management
3===========================================
4
5.. module:: subprocess
6 :synopsis: Subprocess management.
7.. moduleauthor:: Peter Åstrand <astrand@lysator.liu.se>
8.. sectionauthor:: Peter Åstrand <astrand@lysator.liu.se>
9
10
11.. versionadded:: 2.4
12
13The :mod:`subprocess` module allows you to spawn new processes, connect to their
14input/output/error pipes, and obtain their return codes. This module intends to
15replace several other, older modules and functions, such as::
16
17 os.system
18 os.spawn*
19 os.popen*
20 popen2.*
21 commands.*
22
23Information about how the :mod:`subprocess` module can be used to replace these
24modules and functions can be found in the following sections.
25
Georg Brandl68b4e742008-07-01 19:59:00 +000026.. seealso::
27
28 :pep:`324` -- PEP proposing the subprocess module
29
Georg Brandl8ec7f652007-08-15 14:28:01 +000030
31Using the subprocess Module
32---------------------------
33
Nick Coghlan2ed203a2011-10-26 21:05:56 +100034The recommended approach to invoking subprocesses is to use the following
35convenience functions for all use cases they can handle. For more advanced
36use cases, the underlying :class:`Popen` interface can be used directly.
Nick Coghlan86711572011-10-24 22:19:40 +100037
38
Nick Coghlan2ed203a2011-10-26 21:05:56 +100039.. function:: call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
Nick Coghlan86711572011-10-24 22:19:40 +100040
41 Run the command described by *args*. Wait for command to complete, then
42 return the :attr:`returncode` attribute.
43
44 The arguments shown above are merely the most common ones, described below
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
77 :attr:`returncode` attribute.
78
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
117 :attr:`returncode` attribute and any output in the :attr:`output`
118 attribute.
119
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
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000148 .. warning::
149
Nick Coghlan87ba6422011-10-27 17:55:13 +1000150 Invoking the system shell with ``shell=True`` can be a security hazard
151 if combined with untrusted input. See the warning under
152 :ref:`frequently-used-arguments` for details.
153
154 .. note::
155
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000156 Do not use ``stderr=PIPE`` with this function. As the pipe is not being
157 read in the current process, the child process may block if it
158 generates enough output to the pipe to fill up the OS pipe buffer.
159
Nick Coghlan86711572011-10-24 22:19:40 +1000160
161.. data:: PIPE
162
163 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
164 to :class:`Popen` and indicates that a pipe to the standard stream should be
165 opened.
166
167
168.. data:: STDOUT
169
170 Special value that can be used as the *stderr* argument to :class:`Popen` and
171 indicates that standard error should go into the same handle as standard
172 output.
173
174
Andrew Svetlov8afcec42012-08-09 15:23:49 +0300175.. exception:: CalledProcessError
176
177 Exception raised when a process run by :func:`check_call` or
178 :func:`check_output` returns a non-zero exit status.
179
180 .. attribute:: returncode
181
182 Exit status of the child process.
183
184 .. attribute:: cmd
185
186 Command that was used to spawn the child process.
187
188 .. attribute:: output
189
190 Output of the child process if this exception is raised by
191 :func:`check_output`. Otherwise, ``None``.
192
193
194
Nick Coghlan86711572011-10-24 22:19:40 +1000195.. _frequently-used-arguments:
196
197Frequently Used Arguments
198^^^^^^^^^^^^^^^^^^^^^^^^^
199
200To support a wide variety of use cases, the :class:`Popen` constructor (and
201the convenience functions) accept a large number of optional arguments. For
202most typical use cases, many of these arguments can be safely left at their
203default values. The arguments that are most commonly needed are:
204
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000205 *args* is required for all calls and should be a string, or a sequence of
206 program arguments. Providing a sequence of arguments is generally
207 preferred, as it allows the module to take care of any required escaping
208 and quoting of arguments (e.g. to permit spaces in file names). If passing
209 a single string, either *shell* must be :const:`True` (see below) or else
210 the string must simply name the program to be executed without specifying
211 any arguments.
Nick Coghlan86711572011-10-24 22:19:40 +1000212
213 *stdin*, *stdout* and *stderr* specify the executed program's standard input,
214 standard output and standard error file handles, respectively. Valid values
215 are :data:`PIPE`, an existing file descriptor (a positive integer), an
216 existing file object, and ``None``. :data:`PIPE` indicates that a new pipe
217 to the child should be created. With the default settings of ``None``, no
218 redirection will occur; the child's file handles will be inherited from the
219 parent. Additionally, *stderr* can be :data:`STDOUT`, which indicates that
220 the stderr data from the child process should be captured into the same file
221 handle as for stdout.
222
R David Murray5618aaa2012-08-15 11:15:39 -0400223 .. index::
224 single: universal newlines; subprocess module
225
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000226 When *stdout* or *stderr* are pipes and *universal_newlines* is
R David Murray5618aaa2012-08-15 11:15:39 -0400227 ``True`` then all line endings will be converted to ``'\n'`` as described
228 for the :term:`universal newlines` `'U'`` mode argument to :func:`open`.
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000229
Ezio Melottieab4df52012-09-15 08:33:12 +0300230 If *shell* is ``True``, the specified command will be executed through
231 the shell. This can be useful if you are using Python primarily for the
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000232 enhanced control flow it offers over most system shells and still want
Ezio Melottieab4df52012-09-15 08:33:12 +0300233 convenient access to other shell features such as shell pipes, filename
234 wildcards, environment variable expansion, and expansion of ``~`` to a
235 user's home directory. However, note that Python itself offers
236 implementations of many shell-like features (in particular, :mod:`glob`,
237 :mod:`fnmatch`, :func:`os.walk`, :func:`os.path.expandvars`,
238 :func:`os.path.expanduser`, and :mod:`shutil`).
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000239
240 .. warning::
241
242 Executing shell commands that incorporate unsanitized input from an
243 untrusted source makes a program vulnerable to `shell injection
244 <http://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_,
245 a serious security flaw which can result in arbitrary command execution.
246 For this reason, the use of *shell=True* is **strongly discouraged** in cases
247 where the command string is constructed from external input::
248
249 >>> from subprocess import call
250 >>> filename = input("What file would you like to display?\n")
251 What file would you like to display?
252 non_existent; rm -rf / #
253 >>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...
254
255 ``shell=False`` disables all shell based features, but does not suffer
256 from this vulnerability; see the Note in the :class:`Popen` constructor
257 documentation for helpful hints in getting ``shell=False`` to work.
258
Nick Coghlan86711572011-10-24 22:19:40 +1000259These options, along with all of the other options, are described in more
260detail in the :class:`Popen` constructor documentation.
261
262
Sandro Tosidbcbd102011-12-25 11:27:22 +0100263Popen Constructor
Sandro Tosi44585bd2011-12-25 17:13:10 +0100264^^^^^^^^^^^^^^^^^
Nick Coghlan86711572011-10-24 22:19:40 +1000265
266The underlying process creation and management in this module is handled by
267the :class:`Popen` class. It offers a lot of flexibility so that developers
268are able to handle the less common cases not covered by the convenience
269functions.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000270
271
Chris Jerdonek2a6672b2012-10-10 17:55:41 -0700272.. class:: Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, \
273 stderr=None, preexec_fn=None, close_fds=False, shell=False, \
274 cwd=None, env=None, universal_newlines=False, \
275 startupinfo=None, creationflags=0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000276
Chris Jerdonek2a6672b2012-10-10 17:55:41 -0700277 Execute a child program in a new process. On Unix, the class uses
278 :meth:`os.execvp`-like behavior to execute the child program. On Windows,
279 the class uses the Windows ``CreateProcess()`` function. The arguments to
280 :class:`Popen` are as follows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000281
Chris Jerdonek1906c0c2012-10-08 23:18:17 -0700282 *args* should be a sequence of program arguments or else a single string.
283 By default, the program to execute is the first item in *args* if *args* is
Chris Jerdonek2a6672b2012-10-10 17:55:41 -0700284 a sequence. If *args* is a string, the interpretation is
285 platform-dependent and described below. See the *shell* and *executable*
286 arguments for additional differences from the default behavior. Unless
287 otherwise stated, it is recommended to pass *args* as a sequence.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000288
Chris Jerdonek2a6672b2012-10-10 17:55:41 -0700289 On Unix, if *args* is a string, the string is interpreted as the name or
290 path of the program to execute. However, this can only be done if not
291 passing arguments to the program.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000292
Nick Coghlan7dfc9e12010-02-04 12:43:58 +0000293 .. note::
294
295 :meth:`shlex.split` can be useful when determining the correct
296 tokenization for *args*, especially in complex cases::
297
298 >>> import shlex, subprocess
299 >>> command_line = raw_input()
300 /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
301 >>> args = shlex.split(command_line)
302 >>> print args
303 ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
304 >>> p = subprocess.Popen(args) # Success!
305
306 Note in particular that options (such as *-input*) and arguments (such
307 as *eggs.txt*) that are separated by whitespace in the shell go in separate
308 list elements, while arguments that need quoting or backslash escaping when
309 used in the shell (such as filenames containing spaces or the *echo* command
310 shown above) are single list elements.
311
Chris Jerdonek2a6672b2012-10-10 17:55:41 -0700312 On Windows, if *args* is a sequence, it will be converted to a string in a
313 manner described in :ref:`converting-argument-sequence`. This is because
314 the underlying ``CreateProcess()`` operates on strings.
Chris Jerdonek1906c0c2012-10-08 23:18:17 -0700315
316 The *shell* argument (which defaults to *False*) specifies whether to use
Chris Jerdonek2a6672b2012-10-10 17:55:41 -0700317 the shell as the program to execute. If *shell* is *True*, it is
318 recommended to pass *args* as a string rather than as a sequence.
Chris Jerdonek1906c0c2012-10-08 23:18:17 -0700319
320 On Unix with ``shell=True``, the shell defaults to :file:`/bin/sh`. If
321 *args* is a string, the string specifies the command
322 to execute through the shell. This means that the string must be
Nick Coghlan7dfc9e12010-02-04 12:43:58 +0000323 formatted exactly as it would be when typed at the shell prompt. This
324 includes, for example, quoting or backslash escaping filenames with spaces in
325 them. If *args* is a sequence, the first item specifies the command string, and
326 any additional items will be treated as additional arguments to the shell
Chris Jerdonek1906c0c2012-10-08 23:18:17 -0700327 itself. That is to say, :class:`Popen` does the equivalent of::
Nick Coghlan7dfc9e12010-02-04 12:43:58 +0000328
329 Popen(['/bin/sh', '-c', args[0], args[1], ...])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000330
Chris Jerdonek1906c0c2012-10-08 23:18:17 -0700331 On Windows with ``shell=True``, the :envvar:`COMSPEC` environment variable
332 specifies the default shell. The only time you need to specify
333 ``shell=True`` on Windows is when the command you wish to execute is built
334 into the shell (e.g. :command:`dir` or :command:`copy`). You do not need
335 ``shell=True`` to run a batch file or console-based executable.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000336
337 *bufsize*, if given, has the same meaning as the corresponding argument to the
338 built-in open() function: :const:`0` means unbuffered, :const:`1` means line
339 buffered, any other positive value means use a buffer of (approximately) that
340 size. A negative *bufsize* means to use the system default, which usually means
341 fully buffered. The default value for *bufsize* is :const:`0` (unbuffered).
342
Antoine Pitrouc3955452010-06-02 17:08:47 +0000343 .. note::
344
345 If you experience performance issues, it is recommended that you try to
346 enable buffering by setting *bufsize* to either -1 or a large enough
347 positive value (such as 4096).
348
Chris Jerdonek1906c0c2012-10-08 23:18:17 -0700349 The *executable* argument specifies a replacement program to execute. It
350 is very seldom needed. When ``shell=False``, *executable* replaces the
Chris Jerdonek2a6672b2012-10-10 17:55:41 -0700351 program to execute specified by *args*. However, the original *args* is
352 still passed to the program. Most programs treat the program specified
353 by *args* as the command name, which can then be different from the program
354 actually executed. On Unix, the *args* name
Chris Jerdonek1906c0c2012-10-08 23:18:17 -0700355 becomes the display name for the executable in utilities such as
356 :program:`ps`. If ``shell=True``, on Unix the *executable* argument
357 specifies a replacement shell for the default :file:`/bin/sh`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000358
Nick Coghlan86711572011-10-24 22:19:40 +1000359 *stdin*, *stdout* and *stderr* specify the executed program's standard input,
Georg Brandlf5d5a662008-12-06 11:57:12 +0000360 standard output and standard error file handles, respectively. Valid values
361 are :data:`PIPE`, an existing file descriptor (a positive integer), an
362 existing file object, and ``None``. :data:`PIPE` indicates that a new pipe
Nick Coghlan86711572011-10-24 22:19:40 +1000363 to the child should be created. With the default settings of ``None``, no
364 redirection will occur; the child's file handles will be inherited from the
365 parent. Additionally, *stderr* can be :data:`STDOUT`, which indicates that
366 the stderr data from the child process should be captured into the same file
367 handle as for stdout.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000368
369 If *preexec_fn* is set to a callable object, this object will be called in the
370 child process just before the child is executed. (Unix only)
371
372 If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and
373 :const:`2` will be closed before the child process is executed. (Unix only).
374 Or, on Windows, if *close_fds* is true then no handles will be inherited by the
375 child process. Note that on Windows, you cannot set *close_fds* to true and
376 also redirect the standard handles by setting *stdin*, *stdout* or *stderr*.
377
378 If *shell* is :const:`True`, the specified command will be executed through the
379 shell.
380
Nick Coghlan87ba6422011-10-27 17:55:13 +1000381 .. warning::
Nick Coghlan65ad31a2011-10-26 21:15:53 +1000382
383 Enabling this option can be a security hazard if combined with untrusted
384 input. See the warning under :ref:`frequently-used-arguments`
385 for details.
386
Georg Brandl8ec7f652007-08-15 14:28:01 +0000387 If *cwd* is not ``None``, the child's current directory will be changed to *cwd*
388 before it is executed. Note that this directory is not considered when
389 searching the executable, so you can't specify the program's path relative to
390 *cwd*.
391
Georg Brandlf801b0f2008-04-19 16:58:49 +0000392 If *env* is not ``None``, it must be a mapping that defines the environment
393 variables for the new process; these are used instead of inheriting the current
394 process' environment, which is the default behavior.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000395
R. David Murray72030812009-04-16 18:12:53 +0000396 .. note::
R. David Murray6076d392009-04-15 22:33:07 +0000397
R. David Murray72030812009-04-16 18:12:53 +0000398 If specified, *env* must provide any variables required
399 for the program to execute. On Windows, in order to run a
400 `side-by-side assembly`_ the specified *env* **must** include a valid
R. David Murray6076d392009-04-15 22:33:07 +0000401 :envvar:`SystemRoot`.
402
R. David Murray72030812009-04-16 18:12:53 +0000403 .. _side-by-side assembly: http://en.wikipedia.org/wiki/Side-by-Side_Assembly
404
R David Murrayc7b8f802012-08-15 11:22:58 -0400405 If *universal_newlines* is ``True``, the file objects *stdout* and *stderr*
406 are opened as text files in :term:`universal newlines` mode. Lines may be
407 terminated by any of ``'\n'``, the Unix end-of-line convention, ``'\r'``,
408 the old Macintosh convention or ``'\r\n'``, the Windows convention. All of
409 these external representations are seen as ``'\n'`` by the Python program.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000410
411 .. note::
412
Georg Brandl6ab5d082009-12-20 14:33:20 +0000413 This feature is only available if Python is built with universal newline
414 support (the default). Also, the newlines attribute of the file objects
415 :attr:`stdout`, :attr:`stdin` and :attr:`stderr` are not updated by the
416 communicate() method.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000417
Brian Curtinbb23bd62011-04-29 22:23:46 -0500418 If given, *startupinfo* will be a :class:`STARTUPINFO` object, which is
419 passed to the underlying ``CreateProcess`` function.
420 *creationflags*, if given, can be :data:`CREATE_NEW_CONSOLE` or
421 :data:`CREATE_NEW_PROCESS_GROUP`. (Windows only)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000422
423
Georg Brandl8ec7f652007-08-15 14:28:01 +0000424Exceptions
425^^^^^^^^^^
426
427Exceptions raised in the child process, before the new program has started to
428execute, will be re-raised in the parent. Additionally, the exception object
429will have one extra attribute called :attr:`child_traceback`, which is a string
Georg Brandl21946af2010-10-06 09:28:45 +0000430containing traceback information from the child's point of view.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000431
432The most common exception raised is :exc:`OSError`. This occurs, for example,
433when trying to execute a non-existent file. Applications should prepare for
434:exc:`OSError` exceptions.
435
436A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid
437arguments.
438
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000439:func:`check_call` and :func:`check_output` will raise
440:exc:`CalledProcessError` if the called process returns a non-zero return
441code.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000442
443
444Security
445^^^^^^^^
446
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000447Unlike some other popen functions, this implementation will never call a
448system shell implicitly. This means that all characters, including shell
449metacharacters, can safely be passed to child processes. Obviously, if the
450shell is invoked explicitly, then it is the application's responsibility to
Nick Coghlan63c54e82011-10-26 21:34:26 +1000451ensure that all whitespace and metacharacters are quoted appropriately.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000452
453
454Popen Objects
455-------------
456
457Instances of the :class:`Popen` class have the following methods:
458
459
460.. method:: Popen.poll()
461
Georg Brandl2cb103f2008-01-06 16:01:26 +0000462 Check if child process has terminated. Set and return :attr:`returncode`
463 attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000464
465
466.. method:: Popen.wait()
467
Georg Brandl2cb103f2008-01-06 16:01:26 +0000468 Wait for child process to terminate. Set and return :attr:`returncode`
469 attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000470
Georg Brandl143de622008-08-04 06:29:36 +0000471 .. warning::
472
Philip Jenvey26275532009-12-03 02:25:54 +0000473 This will deadlock when using ``stdout=PIPE`` and/or
474 ``stderr=PIPE`` and the child process generates enough output to
475 a pipe such that it blocks waiting for the OS pipe buffer to
476 accept more data. Use :meth:`communicate` to avoid that.
Gregory P. Smith08792502008-08-04 01:03:50 +0000477
Georg Brandl8ec7f652007-08-15 14:28:01 +0000478
479.. method:: Popen.communicate(input=None)
480
481 Interact with process: Send data to stdin. Read data from stdout and stderr,
482 until end-of-file is reached. Wait for process to terminate. The optional
483 *input* argument should be a string to be sent to the child process, or
484 ``None``, if no data should be sent to the child.
485
Georg Brandl17432012008-12-04 21:28:16 +0000486 :meth:`communicate` returns a tuple ``(stdoutdata, stderrdata)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000487
Georg Brandl439f2502007-11-24 11:31:46 +0000488 Note that if you want to send data to the process's stdin, you need to create
489 the Popen object with ``stdin=PIPE``. Similarly, to get anything other than
490 ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or
491 ``stderr=PIPE`` too.
492
Georg Brandl2cb103f2008-01-06 16:01:26 +0000493 .. note::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000494
Georg Brandl2cb103f2008-01-06 16:01:26 +0000495 The data read is buffered in memory, so do not use this method if the data
496 size is large or unlimited.
497
Georg Brandl8ec7f652007-08-15 14:28:01 +0000498
Christian Heimese74c8f22008-04-19 02:23:57 +0000499.. method:: Popen.send_signal(signal)
500
501 Sends the signal *signal* to the child.
502
503 .. note::
504
Brian Curtine5aa8862010-04-02 23:26:06 +0000505 On Windows, SIGTERM is an alias for :meth:`terminate`. CTRL_C_EVENT and
Ezio Melotti9ccc5812010-04-05 08:16:41 +0000506 CTRL_BREAK_EVENT can be sent to processes started with a *creationflags*
Brian Curtine5aa8862010-04-02 23:26:06 +0000507 parameter which includes `CREATE_NEW_PROCESS_GROUP`.
Georg Brandl734de682008-04-19 08:23:59 +0000508
509 .. versionadded:: 2.6
Christian Heimese74c8f22008-04-19 02:23:57 +0000510
511
512.. method:: Popen.terminate()
513
514 Stop the child. On Posix OSs the method sends SIGTERM to the
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100515 child. On Windows the Win32 API function :c:func:`TerminateProcess` is called
Christian Heimese74c8f22008-04-19 02:23:57 +0000516 to stop the child.
517
Georg Brandl734de682008-04-19 08:23:59 +0000518 .. versionadded:: 2.6
519
Christian Heimese74c8f22008-04-19 02:23:57 +0000520
521.. method:: Popen.kill()
522
523 Kills the child. On Posix OSs the function sends SIGKILL to the child.
Georg Brandl734de682008-04-19 08:23:59 +0000524 On Windows :meth:`kill` is an alias for :meth:`terminate`.
525
526 .. versionadded:: 2.6
Christian Heimese74c8f22008-04-19 02:23:57 +0000527
528
Georg Brandl8ec7f652007-08-15 14:28:01 +0000529The following attributes are also available:
530
Georg Brandl143de622008-08-04 06:29:36 +0000531.. warning::
532
Ezio Melotti8662c842012-08-27 10:00:05 +0300533 Use :meth:`~Popen.communicate` rather than :attr:`.stdin.write <Popen.stdin>`,
534 :attr:`.stdout.read <Popen.stdout>` or :attr:`.stderr.read <Popen.stderr>` to avoid
Georg Brandl16a57f62009-04-27 15:29:09 +0000535 deadlocks due to any of the other OS pipe buffers filling up and blocking the
536 child process.
Georg Brandl143de622008-08-04 06:29:36 +0000537
538
Georg Brandl8ec7f652007-08-15 14:28:01 +0000539.. attribute:: Popen.stdin
540
Georg Brandlf5d5a662008-12-06 11:57:12 +0000541 If the *stdin* argument was :data:`PIPE`, this attribute is a file object
542 that provides input to the child process. Otherwise, it is ``None``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000543
544
545.. attribute:: Popen.stdout
546
Georg Brandlf5d5a662008-12-06 11:57:12 +0000547 If the *stdout* argument was :data:`PIPE`, this attribute is a file object
548 that provides output from the child process. Otherwise, it is ``None``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000549
550
551.. attribute:: Popen.stderr
552
Georg Brandlf5d5a662008-12-06 11:57:12 +0000553 If the *stderr* argument was :data:`PIPE`, this attribute is a file object
554 that provides error output from the child process. Otherwise, it is
555 ``None``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000556
557
558.. attribute:: Popen.pid
559
560 The process ID of the child process.
561
Georg Brandl0b56ce02010-03-21 09:28:16 +0000562 Note that if you set the *shell* argument to ``True``, this is the process ID
563 of the spawned shell.
564
Georg Brandl8ec7f652007-08-15 14:28:01 +0000565
566.. attribute:: Popen.returncode
567
Georg Brandl2cb103f2008-01-06 16:01:26 +0000568 The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly
569 by :meth:`communicate`). A ``None`` value indicates that the process
570 hasn't terminated yet.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000571
Georg Brandl2cb103f2008-01-06 16:01:26 +0000572 A negative value ``-N`` indicates that the child was terminated by signal
573 ``N`` (Unix only).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000574
575
Brian Curtinbb23bd62011-04-29 22:23:46 -0500576Windows Popen Helpers
577---------------------
578
579The :class:`STARTUPINFO` class and following constants are only available
580on Windows.
581
582.. class:: STARTUPINFO()
583
584 Partial support of the Windows
585 `STARTUPINFO <http://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx>`__
586 structure is used for :class:`Popen` creation.
587
588 .. attribute:: dwFlags
589
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700590 A bit field that determines whether certain :class:`STARTUPINFO`
591 attributes are used when the process creates a window. ::
Brian Curtinbb23bd62011-04-29 22:23:46 -0500592
593 si = subprocess.STARTUPINFO()
594 si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
595
596 .. attribute:: hStdInput
597
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700598 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
599 is the standard input handle for the process. If
600 :data:`STARTF_USESTDHANDLES` is not specified, the default for standard
601 input is the keyboard buffer.
Brian Curtinbb23bd62011-04-29 22:23:46 -0500602
603 .. attribute:: hStdOutput
604
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700605 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
606 is the standard output handle for the process. Otherwise, this attribute
607 is ignored and the default for standard output is the console window's
Brian Curtinbb23bd62011-04-29 22:23:46 -0500608 buffer.
609
610 .. attribute:: hStdError
611
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700612 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
613 is the standard error handle for the process. Otherwise, this attribute is
Brian Curtinbb23bd62011-04-29 22:23:46 -0500614 ignored and the default for standard error is the console window's buffer.
615
616 .. attribute:: wShowWindow
617
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700618 If :attr:`dwFlags` specifies :data:`STARTF_USESHOWWINDOW`, this attribute
Brian Curtinbb23bd62011-04-29 22:23:46 -0500619 can be any of the values that can be specified in the ``nCmdShow``
620 parameter for the
621 `ShowWindow <http://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx>`__
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700622 function, except for ``SW_SHOWDEFAULT``. Otherwise, this attribute is
Brian Curtinbb23bd62011-04-29 22:23:46 -0500623 ignored.
624
625 :data:`SW_HIDE` is provided for this attribute. It is used when
626 :class:`Popen` is called with ``shell=True``.
627
628
629Constants
630^^^^^^^^^
631
632The :mod:`subprocess` module exposes the following constants.
633
634.. data:: STD_INPUT_HANDLE
635
636 The standard input device. Initially, this is the console input buffer,
637 ``CONIN$``.
638
639.. data:: STD_OUTPUT_HANDLE
640
641 The standard output device. Initially, this is the active console screen
642 buffer, ``CONOUT$``.
643
644.. data:: STD_ERROR_HANDLE
645
646 The standard error device. Initially, this is the active console screen
647 buffer, ``CONOUT$``.
648
649.. data:: SW_HIDE
650
651 Hides the window. Another window will be activated.
652
653.. data:: STARTF_USESTDHANDLES
654
655 Specifies that the :attr:`STARTUPINFO.hStdInput`,
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700656 :attr:`STARTUPINFO.hStdOutput`, and :attr:`STARTUPINFO.hStdError` attributes
Brian Curtinbb23bd62011-04-29 22:23:46 -0500657 contain additional information.
658
659.. data:: STARTF_USESHOWWINDOW
660
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700661 Specifies that the :attr:`STARTUPINFO.wShowWindow` attribute contains
Brian Curtinbb23bd62011-04-29 22:23:46 -0500662 additional information.
663
664.. data:: CREATE_NEW_CONSOLE
665
666 The new process has a new console, instead of inheriting its parent's
667 console (the default).
668
669 This flag is always set when :class:`Popen` is created with ``shell=True``.
670
671.. data:: CREATE_NEW_PROCESS_GROUP
672
673 A :class:`Popen` ``creationflags`` parameter to specify that a new process
674 group will be created. This flag is necessary for using :func:`os.kill`
675 on the subprocess.
676
677 This flag is ignored if :data:`CREATE_NEW_CONSOLE` is specified.
678
679
Georg Brandl0ba92b22008-06-22 09:05:29 +0000680.. _subprocess-replacements:
681
Georg Brandl8ec7f652007-08-15 14:28:01 +0000682Replacing Older Functions with the subprocess Module
683----------------------------------------------------
684
Nick Coghlan86711572011-10-24 22:19:40 +1000685In this section, "a becomes b" means that b can be used as a replacement for a.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000686
687.. note::
688
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000689 All "a" functions in this section fail (more or less) silently if the
690 executed program cannot be found; the "b" replacements raise :exc:`OSError`
691 instead.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000692
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000693 In addition, the replacements using :func:`check_output` will fail with a
694 :exc:`CalledProcessError` if the requested operation produces a non-zero
695 return code. The output is still available as the ``output`` attribute of
696 the raised exception.
697
698In the following examples, we assume that the relevant functions have already
699been imported from the subprocess module.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000700
701
702Replacing /bin/sh shell backquote
703^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
704
705::
706
707 output=`mycmd myarg`
Nick Coghlan86711572011-10-24 22:19:40 +1000708 # becomes
709 output = check_output(["mycmd", "myarg"])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000710
711
Benjamin Petersoncae58482008-10-10 20:38:49 +0000712Replacing shell pipeline
713^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +0000714
715::
716
717 output=`dmesg | grep hda`
Nick Coghlan86711572011-10-24 22:19:40 +1000718 # becomes
Georg Brandl8ec7f652007-08-15 14:28:01 +0000719 p1 = Popen(["dmesg"], stdout=PIPE)
720 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Gregory P. Smithe3e967f2011-02-05 21:49:56 +0000721 p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000722 output = p2.communicate()[0]
723
Gregory P. Smithe3e967f2011-02-05 21:49:56 +0000724The p1.stdout.close() call after starting the p2 is important in order for p1
725to receive a SIGPIPE if p2 exits before p1.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000726
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000727Alternatively, for trusted input, the shell's own pipeline support may still
R David Murray5fc56eb2012-04-03 08:46:05 -0400728be used directly::
Nick Coghlan86711572011-10-24 22:19:40 +1000729
730 output=`dmesg | grep hda`
731 # becomes
732 output=check_output("dmesg | grep hda", shell=True)
733
734
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000735Replacing :func:`os.system`
736^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +0000737
738::
739
740 sts = os.system("mycmd" + " myarg")
Nick Coghlan86711572011-10-24 22:19:40 +1000741 # becomes
742 sts = call("mycmd" + " myarg", shell=True)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000743
744Notes:
745
746* Calling the program through the shell is usually not required.
747
Georg Brandl8ec7f652007-08-15 14:28:01 +0000748A more realistic example would look like this::
749
750 try:
751 retcode = call("mycmd" + " myarg", shell=True)
752 if retcode < 0:
753 print >>sys.stderr, "Child was terminated by signal", -retcode
754 else:
755 print >>sys.stderr, "Child returned", retcode
756 except OSError, e:
757 print >>sys.stderr, "Execution failed:", e
758
759
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000760Replacing the :func:`os.spawn <os.spawnl>` family
761^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +0000762
763P_NOWAIT example::
764
765 pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
766 ==>
767 pid = Popen(["/bin/mycmd", "myarg"]).pid
768
769P_WAIT example::
770
771 retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
772 ==>
773 retcode = call(["/bin/mycmd", "myarg"])
774
775Vector example::
776
777 os.spawnvp(os.P_NOWAIT, path, args)
778 ==>
779 Popen([path] + args[1:])
780
781Environment example::
782
783 os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
784 ==>
785 Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
786
787
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000788Replacing :func:`os.popen`, :func:`os.popen2`, :func:`os.popen3`
789^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +0000790
791::
792
Philip Jenvey8b902042009-09-29 19:10:15 +0000793 pipe = os.popen("cmd", 'r', bufsize)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000794 ==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000795 pipe = Popen("cmd", shell=True, bufsize=bufsize, stdout=PIPE).stdout
Georg Brandl8ec7f652007-08-15 14:28:01 +0000796
797::
798
Philip Jenvey8b902042009-09-29 19:10:15 +0000799 pipe = os.popen("cmd", 'w', bufsize)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000800 ==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000801 pipe = Popen("cmd", shell=True, bufsize=bufsize, stdin=PIPE).stdin
Georg Brandl8ec7f652007-08-15 14:28:01 +0000802
803::
804
Philip Jenvey8b902042009-09-29 19:10:15 +0000805 (child_stdin, child_stdout) = os.popen2("cmd", mode, bufsize)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000806 ==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000807 p = Popen("cmd", shell=True, bufsize=bufsize,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000808 stdin=PIPE, stdout=PIPE, close_fds=True)
809 (child_stdin, child_stdout) = (p.stdin, p.stdout)
810
811::
812
813 (child_stdin,
814 child_stdout,
Philip Jenvey8b902042009-09-29 19:10:15 +0000815 child_stderr) = os.popen3("cmd", mode, bufsize)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000816 ==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000817 p = Popen("cmd", shell=True, bufsize=bufsize,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000818 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
819 (child_stdin,
820 child_stdout,
821 child_stderr) = (p.stdin, p.stdout, p.stderr)
822
823::
824
Philip Jenvey8b902042009-09-29 19:10:15 +0000825 (child_stdin, child_stdout_and_stderr) = os.popen4("cmd", mode,
826 bufsize)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000827 ==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000828 p = Popen("cmd", shell=True, bufsize=bufsize,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000829 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
830 (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
831
Philip Jenvey8b902042009-09-29 19:10:15 +0000832On Unix, os.popen2, os.popen3 and os.popen4 also accept a sequence as
833the command to execute, in which case arguments will be passed
834directly to the program without shell intervention. This usage can be
835replaced as follows::
836
837 (child_stdin, child_stdout) = os.popen2(["/bin/ls", "-l"], mode,
838 bufsize)
839 ==>
840 p = Popen(["/bin/ls", "-l"], bufsize=bufsize, stdin=PIPE, stdout=PIPE)
841 (child_stdin, child_stdout) = (p.stdin, p.stdout)
842
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000843Return code handling translates as follows::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000844
Philip Jenvey8b902042009-09-29 19:10:15 +0000845 pipe = os.popen("cmd", 'w')
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000846 ...
847 rc = pipe.close()
Stefan Kraha253dc12010-07-14 10:06:07 +0000848 if rc is not None and rc >> 8:
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000849 print "There were some errors"
850 ==>
Philip Jenvey8b902042009-09-29 19:10:15 +0000851 process = Popen("cmd", 'w', shell=True, stdin=PIPE)
R. David Murrayccb9d4b2009-06-09 00:44:22 +0000852 ...
853 process.stdin.close()
854 if process.wait() != 0:
855 print "There were some errors"
856
857
858Replacing functions from the :mod:`popen2` module
859^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl8ec7f652007-08-15 14:28:01 +0000860
Georg Brandl8ec7f652007-08-15 14:28:01 +0000861::
862
863 (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
864 ==>
865 p = Popen(["somestring"], shell=True, bufsize=bufsize,
866 stdin=PIPE, stdout=PIPE, close_fds=True)
867 (child_stdout, child_stdin) = (p.stdout, p.stdin)
868
Philip Jenvey8b902042009-09-29 19:10:15 +0000869On Unix, popen2 also accepts a sequence as the command to execute, in
870which case arguments will be passed directly to the program without
871shell intervention. This usage can be replaced as follows::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000872
Philip Jenvey8b902042009-09-29 19:10:15 +0000873 (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize,
874 mode)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000875 ==>
876 p = Popen(["mycmd", "myarg"], bufsize=bufsize,
877 stdin=PIPE, stdout=PIPE, close_fds=True)
878 (child_stdout, child_stdin) = (p.stdout, p.stdin)
879
Georg Brandlf5d5a662008-12-06 11:57:12 +0000880:class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as
881:class:`subprocess.Popen`, except that:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000882
Georg Brandlf5d5a662008-12-06 11:57:12 +0000883* :class:`Popen` raises an exception if the execution fails.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000884
885* the *capturestderr* argument is replaced with the *stderr* argument.
886
Georg Brandlf5d5a662008-12-06 11:57:12 +0000887* ``stdin=PIPE`` and ``stdout=PIPE`` must be specified.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000888
889* popen2 closes all file descriptors by default, but you have to specify
Georg Brandlf5d5a662008-12-06 11:57:12 +0000890 ``close_fds=True`` with :class:`Popen`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000891
Nick Coghlan2ed203a2011-10-26 21:05:56 +1000892
Eli Bendersky929e2762011-04-15 07:35:06 +0300893Notes
894-----
895
896.. _converting-argument-sequence:
897
898Converting an argument sequence to a string on Windows
899^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
900
901On Windows, an *args* sequence is converted to a string that can be parsed
902using the following rules (which correspond to the rules used by the MS C
903runtime):
904
9051. Arguments are delimited by white space, which is either a
906 space or a tab.
907
9082. A string surrounded by double quotation marks is
909 interpreted as a single argument, regardless of white space
910 contained within. A quoted string can be embedded in an
911 argument.
912
9133. A double quotation mark preceded by a backslash is
914 interpreted as a literal double quotation mark.
915
9164. Backslashes are interpreted literally, unless they
917 immediately precede a double quotation mark.
918
9195. If backslashes immediately precede a double quotation mark,
920 every pair of backslashes is interpreted as a literal
921 backslash. If the number of backslashes is odd, the last
922 backslash escapes the next double quotation mark as
923 described in rule 3.
924