blob: 932ca8b0841080a1a9baf7ed472575a57fa5ea8b [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`subprocess` --- Subprocess management
2===========================================
3
4.. module:: subprocess
5 :synopsis: Subprocess management.
6.. moduleauthor:: Peter Åstrand <astrand@lysator.liu.se>
7.. sectionauthor:: Peter Åstrand <astrand@lysator.liu.se>
8
9
Georg Brandl116aa622007-08-15 14:28:22 +000010The :mod:`subprocess` module allows you to spawn new processes, connect to their
11input/output/error pipes, and obtain their return codes. This module intends to
12replace several other, older modules and functions, such as::
13
14 os.system
15 os.spawn*
Georg Brandl116aa622007-08-15 14:28:22 +000016
17Information about how the :mod:`subprocess` module can be used to replace these
18modules and functions can be found in the following sections.
19
Benjamin Peterson41181742008-07-02 20:22:54 +000020.. seealso::
21
22 :pep:`324` -- PEP proposing the subprocess module
23
Georg Brandl116aa622007-08-15 14:28:22 +000024
25Using the subprocess Module
26---------------------------
27
28This module defines one class called :class:`Popen`:
29
30
31.. class:: Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)
32
33 Arguments are:
34
Benjamin Petersond18de0e2008-07-31 20:21:46 +000035 *args* should be a string, or a sequence of program arguments. The program
Benjamin Petersonfa0d7032009-06-01 22:42:33 +000036 to execute is normally the first item in the args sequence or the string if
37 a string is given, but can be explicitly set by using the *executable*
38 argument. When *executable* is given, the first item in the args sequence
39 is still treated by most programs as the command name, which can then be
40 different from the actual executable name. On Unix, it becomes the display
41 name for the executing program in utilities such as :program:`ps`.
Georg Brandl116aa622007-08-15 14:28:22 +000042
43 On Unix, with *shell=False* (default): In this case, the Popen class uses
44 :meth:`os.execvp` to execute the child program. *args* should normally be a
R. David Murray13cc4fd2010-02-04 16:44:31 +000045 sequence. If a string is specified for *args*, it will be used as the name
46 or path of the program to execute; this will only work if the program is
47 being given no arguments.
Georg Brandl116aa622007-08-15 14:28:22 +000048
R. David Murray13cc4fd2010-02-04 16:44:31 +000049 .. note::
50
51 :meth:`shlex.split` can be useful when determining the correct
52 tokenization for *args*, especially in complex cases::
53
54 >>> import shlex, subprocess
R. David Murray2c4f8d12010-02-05 16:26:37 +000055 >>> command_line = input()
R. David Murray13cc4fd2010-02-04 16:44:31 +000056 /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
57 >>> args = shlex.split(command_line)
58 >>> print(args)
59 ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
60 >>> p = subprocess.Popen(args) # Success!
61
62 Note in particular that options (such as *-input*) and arguments (such
63 as *eggs.txt*) that are separated by whitespace in the shell go in separate
64 list elements, while arguments that need quoting or backslash escaping when
65 used in the shell (such as filenames containing spaces or the *echo* command
66 shown above) are single list elements.
67
68 On Unix, with *shell=True*: If args is a string, it specifies the command
69 string to execute through the shell. This means that the string must be
70 formatted exactly as it would be when typed at the shell prompt. This
71 includes, for example, quoting or backslash escaping filenames with spaces in
72 them. If *args* is a sequence, the first item specifies the command string, and
73 any additional items will be treated as additional arguments to the shell
74 itself. That is to say, *Popen* does the equivalent of::
75
76 Popen(['/bin/sh', '-c', args[0], args[1], ...])
Georg Brandl116aa622007-08-15 14:28:22 +000077
R. David Murrayf959b7f2010-11-12 00:38:41 +000078 .. warning::
79
80 Executing shell commands that incorporate unsanitized input from an
81 untrusted source makes a program vulnerable to `shell injection
82 <http://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_,
83 a serious security flaw which can result in arbitrary command execution.
84 For this reason, the use of *shell=True* is **strongly discouraged** in cases
85 where the command string is constructed from external input::
86
87 >>> from subprocess import call
88 >>> filename = input("What file would you like to display?\n")
89 What file would you like to display?
90 non_existent; rm -rf / #
91 >>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...
92
93 *shell=False* does not suffer from this vulnerability; the above Note may be
94 helpful in getting code using *shell=False* to work.
95
Eli Bendersky046a7642011-04-15 07:23:26 +030096 On Windows: the :class:`Popen` class uses CreateProcess() to execute the
97 child program, which operates on strings. If *args* is a sequence, it will
98 be converted to a string in a manner described in
99 :ref:`converting-argument-sequence`.
Georg Brandl116aa622007-08-15 14:28:22 +0000100
101 *bufsize*, if given, has the same meaning as the corresponding argument to the
102 built-in open() function: :const:`0` means unbuffered, :const:`1` means line
103 buffered, any other positive value means use a buffer of (approximately) that
104 size. A negative *bufsize* means to use the system default, which usually means
105 fully buffered. The default value for *bufsize* is :const:`0` (unbuffered).
106
Antoine Pitrou5050bb22010-06-02 17:11:32 +0000107 .. note::
108
109 If you experience performance issues, it is recommended that you try to
110 enable buffering by setting *bufsize* to either -1 or a large enough
111 positive value (such as 4096).
112
Georg Brandl116aa622007-08-15 14:28:22 +0000113 The *executable* argument specifies the program to execute. It is very seldom
114 needed: Usually, the program to execute is defined by the *args* argument. If
115 ``shell=True``, the *executable* argument specifies which shell to use. On Unix,
116 the default shell is :file:`/bin/sh`. On Windows, the default shell is
Georg Brandlbcc484e2009-08-13 11:51:54 +0000117 specified by the :envvar:`COMSPEC` environment variable. The only reason you
118 would need to specify ``shell=True`` on Windows is where the command you
119 wish to execute is actually built in to the shell, eg ``dir``, ``copy``.
120 You don't need ``shell=True`` to run a batch file, nor to run a console-based
121 executable.
Georg Brandl116aa622007-08-15 14:28:22 +0000122
123 *stdin*, *stdout* and *stderr* specify the executed programs' standard input,
Georg Brandlaf265f42008-12-07 15:06:20 +0000124 standard output and standard error file handles, respectively. Valid values
125 are :data:`PIPE`, an existing file descriptor (a positive integer), an
Antoine Pitrou25d535e2010-09-15 11:25:11 +0000126 existing :term:`file object`, and ``None``. :data:`PIPE` indicates that a
127 new pipe to the child should be created. With ``None``, no redirection will
128 occur; the child's file handles will be inherited from the parent. Additionally,
Georg Brandlaf265f42008-12-07 15:06:20 +0000129 *stderr* can be :data:`STDOUT`, which indicates that the stderr data from the
130 applications should be captured into the same file handle as for stdout.
Georg Brandl116aa622007-08-15 14:28:22 +0000131
132 If *preexec_fn* is set to a callable object, this object will be called in the
133 child process just before the child is executed. (Unix only)
134
135 If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and
136 :const:`2` will be closed before the child process is executed. (Unix only).
137 Or, on Windows, if *close_fds* is true then no handles will be inherited by the
138 child process. Note that on Windows, you cannot set *close_fds* to true and
139 also redirect the standard handles by setting *stdin*, *stdout* or *stderr*.
140
141 If *shell* is :const:`True`, the specified command will be executed through the
142 shell.
143
144 If *cwd* is not ``None``, the child's current directory will be changed to *cwd*
145 before it is executed. Note that this directory is not considered when
146 searching the executable, so you can't specify the program's path relative to
147 *cwd*.
148
Christian Heimesa342c012008-04-20 21:01:16 +0000149 If *env* is not ``None``, it must be a mapping that defines the environment
150 variables for the new process; these are used instead of inheriting the current
151 process' environment, which is the default behavior.
Georg Brandl116aa622007-08-15 14:28:22 +0000152
R. David Murray1055e892009-04-16 18:15:32 +0000153 .. note::
R. David Murrayf4ac1492009-04-15 22:35:15 +0000154
Georg Brandl8ffe0bc2010-10-06 07:17:29 +0000155 If specified, *env* must provide any variables required for the program to
156 execute. On Windows, in order to run a `side-by-side assembly`_ the
157 specified *env* **must** include a valid :envvar:`SystemRoot`.
R. David Murrayf4ac1492009-04-15 22:35:15 +0000158
R. David Murray1055e892009-04-16 18:15:32 +0000159 .. _side-by-side assembly: http://en.wikipedia.org/wiki/Side-by-Side_Assembly
160
Georg Brandl116aa622007-08-15 14:28:22 +0000161 If *universal_newlines* is :const:`True`, the file objects stdout and stderr are
162 opened as text files, but lines may be terminated by any of ``'\n'``, the Unix
Georg Brandlc575c902008-09-13 17:46:05 +0000163 end-of-line convention, ``'\r'``, the old Macintosh convention or ``'\r\n'``, the
Georg Brandl116aa622007-08-15 14:28:22 +0000164 Windows convention. All of these external representations are seen as ``'\n'``
165 by the Python program.
166
167 .. note::
168
Georg Brandlb044b2a2009-09-16 16:05:59 +0000169 This feature is only available if Python is built with universal newline
170 support (the default). Also, the newlines attribute of the file objects
171 :attr:`stdout`, :attr:`stdin` and :attr:`stderr` are not updated by the
172 :meth:`communicate` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000173
Brian Curtine6242d72011-04-29 22:17:51 -0500174 If given, *startupinfo* will be a :class:`STARTUPINFO` object, which is
175 passed to the underlying ``CreateProcess`` function.
176 *creationflags*, if given, can be :data:`CREATE_NEW_CONSOLE`. (Windows only)
Georg Brandl116aa622007-08-15 14:28:22 +0000177
178
Georg Brandlaf265f42008-12-07 15:06:20 +0000179.. data:: PIPE
180
181 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
182 to :class:`Popen` and indicates that a pipe to the standard stream should be
183 opened.
184
185
186.. data:: STDOUT
187
188 Special value that can be used as the *stderr* argument to :class:`Popen` and
189 indicates that standard error should go into the same handle as standard
190 output.
Georg Brandl48310cd2009-01-03 21:18:54 +0000191
Georg Brandlaf265f42008-12-07 15:06:20 +0000192
Georg Brandl116aa622007-08-15 14:28:22 +0000193Convenience Functions
194^^^^^^^^^^^^^^^^^^^^^
195
Ezio Melotti8dfcab02011-04-19 23:15:13 +0300196This module also defines the following shortcut functions:
Georg Brandl116aa622007-08-15 14:28:22 +0000197
198
199.. function:: call(*popenargs, **kwargs)
200
201 Run command with arguments. Wait for command to complete, then return the
202 :attr:`returncode` attribute.
203
204 The arguments are the same as for the Popen constructor. Example::
205
Georg Brandl8ffe0bc2010-10-06 07:17:29 +0000206 >>> retcode = subprocess.call(["ls", "-l"])
Georg Brandl116aa622007-08-15 14:28:22 +0000207
Philip Jenveyab7481a2009-05-22 05:46:35 +0000208 .. warning::
209
210 Like :meth:`Popen.wait`, this will deadlock if the child process
211 generates enough output to a stdout or stderr pipe such that it blocks
212 waiting for the OS pipe buffer to accept more data.
213
Georg Brandl116aa622007-08-15 14:28:22 +0000214
215.. function:: check_call(*popenargs, **kwargs)
216
217 Run command with arguments. Wait for command to complete. If the exit code was
Benjamin Petersone5384b02008-10-04 22:00:42 +0000218 zero then return, otherwise raise :exc:`CalledProcessError`. The
Georg Brandl116aa622007-08-15 14:28:22 +0000219 :exc:`CalledProcessError` object will have the return code in the
220 :attr:`returncode` attribute.
221
222 The arguments are the same as for the Popen constructor. Example::
223
Georg Brandl8ffe0bc2010-10-06 07:17:29 +0000224 >>> subprocess.check_call(["ls", "-l"])
225 0
Georg Brandl116aa622007-08-15 14:28:22 +0000226
Philip Jenveyab7481a2009-05-22 05:46:35 +0000227 .. warning::
228
229 See the warning for :func:`call`.
230
Georg Brandl116aa622007-08-15 14:28:22 +0000231
Georg Brandlf9734072008-12-07 15:30:06 +0000232.. function:: check_output(*popenargs, **kwargs)
233
234 Run command with arguments and return its output as a byte string.
235
Benjamin Petersonaa069002009-01-23 03:26:36 +0000236 If the exit code was non-zero it raises a :exc:`CalledProcessError`. The
237 :exc:`CalledProcessError` object will have the return code in the
238 :attr:`returncode`
239 attribute and output in the :attr:`output` attribute.
Georg Brandlf9734072008-12-07 15:30:06 +0000240
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000241 The arguments are the same as for the :class:`Popen` constructor. Example::
Georg Brandlf9734072008-12-07 15:30:06 +0000242
243 >>> subprocess.check_output(["ls", "-l", "/dev/null"])
Georg Brandl8ffe0bc2010-10-06 07:17:29 +0000244 b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000245
246 The stdout argument is not allowed as it is used internally.
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000247 To capture standard error in the result, use ``stderr=subprocess.STDOUT``::
Georg Brandlf9734072008-12-07 15:30:06 +0000248
249 >>> subprocess.check_output(
Georg Brandl8ffe0bc2010-10-06 07:17:29 +0000250 ... ["/bin/sh", "-c", "ls non_existent_file; exit 0"],
251 ... stderr=subprocess.STDOUT)
252 b'ls: non_existent_file: No such file or directory\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000253
254 .. versionadded:: 3.1
255
256
Brett Cannona23810f2008-05-26 19:04:21 +0000257.. function:: getstatusoutput(cmd)
Georg Brandld098c3d2010-10-06 10:38:58 +0000258
Brett Cannona23810f2008-05-26 19:04:21 +0000259 Return ``(status, output)`` of executing *cmd* in a shell.
260
261 Execute the string *cmd* in a shell with :func:`os.popen` and return a 2-tuple
262 ``(status, output)``. *cmd* is actually run as ``{ cmd ; } 2>&1``, so that the
263 returned output will contain output or error messages. A trailing newline is
264 stripped from the output. The exit status for the command can be interpreted
265 according to the rules for the C function :cfunc:`wait`. Example::
266
Brett Cannona23810f2008-05-26 19:04:21 +0000267 >>> subprocess.getstatusoutput('ls /bin/ls')
268 (0, '/bin/ls')
269 >>> subprocess.getstatusoutput('cat /bin/junk')
270 (256, 'cat: /bin/junk: No such file or directory')
271 >>> subprocess.getstatusoutput('/bin/junk')
272 (256, 'sh: /bin/junk: not found')
273
Georg Brandl7d418902008-12-27 19:08:11 +0000274 Availability: UNIX.
275
Brett Cannona23810f2008-05-26 19:04:21 +0000276
277.. function:: getoutput(cmd)
Georg Brandld098c3d2010-10-06 10:38:58 +0000278
Georg Brandlf9734072008-12-07 15:30:06 +0000279 Return output (stdout and stderr) of executing *cmd* in a shell.
Brett Cannona23810f2008-05-26 19:04:21 +0000280
281 Like :func:`getstatusoutput`, except the exit status is ignored and the return
282 value is a string containing the command's output. Example::
283
Brett Cannona23810f2008-05-26 19:04:21 +0000284 >>> subprocess.getoutput('ls /bin/ls')
285 '/bin/ls'
286
Georg Brandl7d418902008-12-27 19:08:11 +0000287 Availability: UNIX.
288
Brett Cannona23810f2008-05-26 19:04:21 +0000289
Georg Brandl116aa622007-08-15 14:28:22 +0000290Exceptions
291^^^^^^^^^^
292
293Exceptions raised in the child process, before the new program has started to
294execute, will be re-raised in the parent. Additionally, the exception object
295will have one extra attribute called :attr:`child_traceback`, which is a string
Georg Brandl57a5e3f2010-10-06 08:54:16 +0000296containing traceback information from the child's point of view.
Georg Brandl116aa622007-08-15 14:28:22 +0000297
298The most common exception raised is :exc:`OSError`. This occurs, for example,
299when trying to execute a non-existent file. Applications should prepare for
300:exc:`OSError` exceptions.
301
302A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid
303arguments.
304
305check_call() will raise :exc:`CalledProcessError`, if the called process returns
306a non-zero return code.
307
308
309Security
310^^^^^^^^
311
312Unlike some other popen functions, this implementation will never call /bin/sh
313implicitly. This means that all characters, including shell metacharacters, can
314safely be passed to child processes.
315
316
317Popen Objects
318-------------
319
320Instances of the :class:`Popen` class have the following methods:
321
322
323.. method:: Popen.poll()
324
Christian Heimes7f044312008-01-06 17:05:40 +0000325 Check if child process has terminated. Set and return :attr:`returncode`
326 attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000327
328
329.. method:: Popen.wait()
330
Christian Heimes7f044312008-01-06 17:05:40 +0000331 Wait for child process to terminate. Set and return :attr:`returncode`
332 attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000333
Georg Brandl734e2682008-08-12 08:18:18 +0000334 .. warning::
335
336 This will deadlock if the child process generates enough output to a
337 stdout or stderr pipe such that it blocks waiting for the OS pipe buffer
338 to accept more data. Use :meth:`communicate` to avoid that.
339
Georg Brandl116aa622007-08-15 14:28:22 +0000340
341.. method:: Popen.communicate(input=None)
342
343 Interact with process: Send data to stdin. Read data from stdout and stderr,
344 until end-of-file is reached. Wait for process to terminate. The optional
Georg Brandle11787a2008-07-01 19:10:52 +0000345 *input* argument should be a byte string to be sent to the child process, or
Georg Brandl116aa622007-08-15 14:28:22 +0000346 ``None``, if no data should be sent to the child.
347
Georg Brandlaf265f42008-12-07 15:06:20 +0000348 :meth:`communicate` returns a tuple ``(stdoutdata, stderrdata)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000349
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000350 Note that if you want to send data to the process's stdin, you need to create
351 the Popen object with ``stdin=PIPE``. Similarly, to get anything other than
352 ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or
353 ``stderr=PIPE`` too.
354
Christian Heimes7f044312008-01-06 17:05:40 +0000355 .. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000356
Christian Heimes7f044312008-01-06 17:05:40 +0000357 The data read is buffered in memory, so do not use this method if the data
358 size is large or unlimited.
359
Georg Brandl116aa622007-08-15 14:28:22 +0000360
Christian Heimesa342c012008-04-20 21:01:16 +0000361.. method:: Popen.send_signal(signal)
362
363 Sends the signal *signal* to the child.
364
365 .. note::
366
367 On Windows only SIGTERM is supported so far. It's an alias for
368 :meth:`terminate`.
369
Christian Heimesa342c012008-04-20 21:01:16 +0000370
371.. method:: Popen.terminate()
372
373 Stop the child. On Posix OSs the method sends SIGTERM to the
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000374 child. On Windows the Win32 API function :cfunc:`TerminateProcess` is called
Christian Heimesa342c012008-04-20 21:01:16 +0000375 to stop the child.
376
Christian Heimesa342c012008-04-20 21:01:16 +0000377
378.. method:: Popen.kill()
379
380 Kills the child. On Posix OSs the function sends SIGKILL to the child.
381 On Windows :meth:`kill` is an alias for :meth:`terminate`.
382
Christian Heimesa342c012008-04-20 21:01:16 +0000383
Georg Brandl116aa622007-08-15 14:28:22 +0000384The following attributes are also available:
385
Georg Brandl734e2682008-08-12 08:18:18 +0000386.. warning::
387
Georg Brandle720c0a2009-04-27 16:20:50 +0000388 Use :meth:`communicate` rather than :attr:`.stdin.write <stdin>`,
389 :attr:`.stdout.read <stdout>` or :attr:`.stderr.read <stderr>` to avoid
390 deadlocks due to any of the other OS pipe buffers filling up and blocking the
391 child process.
Georg Brandl734e2682008-08-12 08:18:18 +0000392
393
Georg Brandl116aa622007-08-15 14:28:22 +0000394.. attribute:: Popen.stdin
395
Antoine Pitrou25d535e2010-09-15 11:25:11 +0000396 If the *stdin* argument was :data:`PIPE`, this attribute is a :term:`file
397 object` that provides input to the child process. Otherwise, it is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000398
399
400.. attribute:: Popen.stdout
401
Antoine Pitrou25d535e2010-09-15 11:25:11 +0000402 If the *stdout* argument was :data:`PIPE`, this attribute is a :term:`file
403 object` that provides output from the child process. Otherwise, it is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000404
405
406.. attribute:: Popen.stderr
407
Antoine Pitrou25d535e2010-09-15 11:25:11 +0000408 If the *stderr* argument was :data:`PIPE`, this attribute is a :term:`file
409 object` that provides error output from the child process. Otherwise, it is
Georg Brandlaf265f42008-12-07 15:06:20 +0000410 ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000411
412
413.. attribute:: Popen.pid
414
415 The process ID of the child process.
416
Georg Brandl16215c72010-10-06 07:59:52 +0000417 Note that if you set the *shell* argument to ``True``, this is the process ID
418 of the spawned shell.
419
Georg Brandl116aa622007-08-15 14:28:22 +0000420
421.. attribute:: Popen.returncode
422
Christian Heimes7f044312008-01-06 17:05:40 +0000423 The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly
424 by :meth:`communicate`). A ``None`` value indicates that the process
425 hasn't terminated yet.
Georg Brandl48310cd2009-01-03 21:18:54 +0000426
Christian Heimes7f044312008-01-06 17:05:40 +0000427 A negative value ``-N`` indicates that the child was terminated by signal
428 ``N`` (Unix only).
Georg Brandl116aa622007-08-15 14:28:22 +0000429
430
Brian Curtine6242d72011-04-29 22:17:51 -0500431Windows Popen Helpers
432---------------------
433
434The :class:`STARTUPINFO` class and following constants are only available
435on Windows.
436
437.. class:: STARTUPINFO()
Brian Curtin73365dd2011-04-29 22:18:33 -0500438
Brian Curtine6242d72011-04-29 22:17:51 -0500439 Partial support of the Windows
440 `STARTUPINFO <http://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx>`__
441 structure is used for :class:`Popen` creation.
442
443 .. attribute:: dwFlags
444
445 A bit field that determines whether certain :class:`STARTUPINFO` members
446 are used when the process creates a window. ::
447
448 si = subprocess.STARTUPINFO()
449 si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
450
451 .. attribute:: hStdInput
452
453 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this member is
454 the standard input handle for the process. If :data:`STARTF_USESTDHANDLES`
455 is not specified, the default for standard input is the keyboard buffer.
456
457 .. attribute:: hStdOutput
458
459 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this member is
460 the standard output handle for the process. Otherwise, this member is
461 ignored and the default for standard output is the console window's
462 buffer.
463
464 .. attribute:: hStdError
465
466 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this member is
467 the standard error handle for the process. Otherwise, this member is
468 ignored and the default for standard error is the console window's buffer.
469
470 .. attribute:: wShowWindow
471
472 If :attr:`dwFlags` specifies :data:`STARTF_USESHOWWINDOW`, this member
473 can be any of the values that can be specified in the ``nCmdShow``
474 parameter for the
475 `ShowWindow <http://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx>`__
476 function, except for ``SW_SHOWDEFAULT``. Otherwise, this member is
477 ignored.
Brian Curtin73365dd2011-04-29 22:18:33 -0500478
Brian Curtine6242d72011-04-29 22:17:51 -0500479 :data:`SW_HIDE` is provided for this attribute. It is used when
480 :class:`Popen` is called with ``shell=True``.
481
482
483Constants
484^^^^^^^^^
485
486The :mod:`subprocess` module exposes the following constants.
487
488.. data:: STD_INPUT_HANDLE
489
490 The standard input device. Initially, this is the console input buffer,
491 ``CONIN$``.
492
493.. data:: STD_OUTPUT_HANDLE
494
495 The standard output device. Initially, this is the active console screen
496 buffer, ``CONOUT$``.
497
498.. data:: STD_ERROR_HANDLE
499
500 The standard error device. Initially, this is the active console screen
501 buffer, ``CONOUT$``.
502
503.. data:: SW_HIDE
504
505 Hides the window. Another window will be activated.
506
507.. data:: STARTF_USESTDHANDLES
508
509 Specifies that the :attr:`STARTUPINFO.hStdInput`,
510 :attr:`STARTUPINFO.hStdOutput`, and :attr:`STARTUPINFO.hStdError` members
511 contain additional information.
512
513.. data:: STARTF_USESHOWWINDOW
514
515 Specifies that the :attr:`STARTUPINFO.wShowWindow` member contains
516 additional information.
517
518.. data:: CREATE_NEW_CONSOLE
519
520 The new process has a new console, instead of inheriting its parent's
521 console (the default).
Brian Curtin73365dd2011-04-29 22:18:33 -0500522
Brian Curtine6242d72011-04-29 22:17:51 -0500523 This flag is always set when :class:`Popen` is created with ``shell=True``.
524
525
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000526.. _subprocess-replacements:
527
Georg Brandl116aa622007-08-15 14:28:22 +0000528Replacing Older Functions with the subprocess Module
529----------------------------------------------------
530
531In this section, "a ==> b" means that b can be used as a replacement for a.
532
533.. note::
534
535 All functions in this section fail (more or less) silently if the executed
536 program cannot be found; this module raises an :exc:`OSError` exception.
537
538In the following examples, we assume that the subprocess module is imported with
539"from subprocess import \*".
540
541
542Replacing /bin/sh shell backquote
543^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
544
545::
546
547 output=`mycmd myarg`
548 ==>
549 output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
550
551
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000552Replacing shell pipeline
553^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000554
555::
556
557 output=`dmesg | grep hda`
558 ==>
559 p1 = Popen(["dmesg"], stdout=PIPE)
560 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Gregory P. Smith8095b652011-02-05 21:51:27 +0000561 p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
Georg Brandl116aa622007-08-15 14:28:22 +0000562 output = p2.communicate()[0]
563
Gregory P. Smith8095b652011-02-05 21:51:27 +0000564The p1.stdout.close() call after starting the p2 is important in order for p1
565to receive a SIGPIPE if p2 exits before p1.
Georg Brandl116aa622007-08-15 14:28:22 +0000566
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000567Replacing :func:`os.system`
568^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000569
570::
571
572 sts = os.system("mycmd" + " myarg")
573 ==>
574 p = Popen("mycmd" + " myarg", shell=True)
Georg Brandld80344f2009-08-13 12:26:19 +0000575 sts = os.waitpid(p.pid, 0)[1]
Georg Brandl116aa622007-08-15 14:28:22 +0000576
577Notes:
578
579* Calling the program through the shell is usually not required.
580
581* It's easier to look at the :attr:`returncode` attribute than the exit status.
582
583A more realistic example would look like this::
584
585 try:
586 retcode = call("mycmd" + " myarg", shell=True)
587 if retcode < 0:
Collin Winterc79461b2007-09-01 23:34:30 +0000588 print("Child was terminated by signal", -retcode, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000589 else:
Collin Winterc79461b2007-09-01 23:34:30 +0000590 print("Child returned", retcode, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000591 except OSError as e:
Collin Winterc79461b2007-09-01 23:34:30 +0000592 print("Execution failed:", e, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000593
594
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000595Replacing the :func:`os.spawn <os.spawnl>` family
596^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000597
598P_NOWAIT example::
599
600 pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
601 ==>
602 pid = Popen(["/bin/mycmd", "myarg"]).pid
603
604P_WAIT example::
605
606 retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
607 ==>
608 retcode = call(["/bin/mycmd", "myarg"])
609
610Vector example::
611
612 os.spawnvp(os.P_NOWAIT, path, args)
613 ==>
614 Popen([path] + args[1:])
615
616Environment example::
617
618 os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
619 ==>
620 Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
621
622
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000623
624Replacing :func:`os.popen`, :func:`os.popen2`, :func:`os.popen3`
625^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000626
627::
628
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000629 (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
Georg Brandl116aa622007-08-15 14:28:22 +0000630 ==>
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000631 p = Popen(cmd, shell=True, bufsize=bufsize,
632 stdin=PIPE, stdout=PIPE, close_fds=True)
633 (child_stdin, child_stdout) = (p.stdin, p.stdout)
Georg Brandl116aa622007-08-15 14:28:22 +0000634
635::
636
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000637 (child_stdin,
638 child_stdout,
639 child_stderr) = os.popen3(cmd, mode, bufsize)
Georg Brandl116aa622007-08-15 14:28:22 +0000640 ==>
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000641 p = Popen(cmd, shell=True, bufsize=bufsize,
642 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
643 (child_stdin,
644 child_stdout,
645 child_stderr) = (p.stdin, p.stdout, p.stderr)
646
647::
648
649 (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
650 ==>
651 p = Popen(cmd, shell=True, bufsize=bufsize,
652 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
653 (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
654
655Return code handling translates as follows::
656
657 pipe = os.popen(cmd, 'w')
658 ...
659 rc = pipe.close()
Stefan Krah5a5031f2010-07-14 10:19:40 +0000660 if rc is not None and rc >> 8:
Ezio Melotti713e0422009-09-13 08:13:21 +0000661 print("There were some errors")
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000662 ==>
663 process = Popen(cmd, 'w', stdin=PIPE)
664 ...
665 process.stdin.close()
666 if process.wait() != 0:
Ezio Melotti713e0422009-09-13 08:13:21 +0000667 print("There were some errors")
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000668
669
670Replacing functions from the :mod:`popen2` module
671^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
672
673.. note::
674
675 If the cmd argument to popen2 functions is a string, the command is executed
676 through /bin/sh. If it is a list, the command is directly executed.
677
678::
679
680 (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
681 ==>
682 p = Popen(["somestring"], shell=True, bufsize=bufsize,
683 stdin=PIPE, stdout=PIPE, close_fds=True)
684 (child_stdout, child_stdin) = (p.stdout, p.stdin)
685
686::
687
688 (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
689 ==>
690 p = Popen(["mycmd", "myarg"], bufsize=bufsize,
691 stdin=PIPE, stdout=PIPE, close_fds=True)
692 (child_stdout, child_stdin) = (p.stdout, p.stdin)
693
694:class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as
695:class:`subprocess.Popen`, except that:
696
697* :class:`Popen` raises an exception if the execution fails.
698
699* the *capturestderr* argument is replaced with the *stderr* argument.
700
701* ``stdin=PIPE`` and ``stdout=PIPE`` must be specified.
702
703* popen2 closes all file descriptors by default, but you have to specify
704 ``close_fds=True`` with :class:`Popen`.
Eli Bendersky046a7642011-04-15 07:23:26 +0300705
706Notes
707-----
708
709.. _converting-argument-sequence:
710
711Converting an argument sequence to a string on Windows
712^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
713
714On Windows, an *args* sequence is converted to a string that can be parsed
715using the following rules (which correspond to the rules used by the MS C
716runtime):
717
7181. Arguments are delimited by white space, which is either a
719 space or a tab.
720
7212. A string surrounded by double quotation marks is
722 interpreted as a single argument, regardless of white space
723 contained within. A quoted string can be embedded in an
724 argument.
725
7263. A double quotation mark preceded by a backslash is
727 interpreted as a literal double quotation mark.
728
7294. Backslashes are interpreted literally, unless they
730 immediately precede a double quotation mark.
731
7325. If backslashes immediately precede a double quotation mark,
733 every pair of backslashes is interpreted as a literal
734 backslash. If the number of backslashes is odd, the last
735 backslash escapes the next double quotation mark as
736 described in rule 3.
737