blob: a0d847139a9f2971bc27c06f6ccaaa81b676bf82 [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
Gregory P. Smith8edd99d2010-12-14 13:43:30 +000031.. class:: Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=())
Georg Brandl116aa622007-08-15 14:28:22 +000032
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
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000044 :meth:`os.execvp` like behavior to execute the child program.
45 *args* should normally be a
R. David Murray5973e4d2010-02-04 16:41:57 +000046 sequence. If a string is specified for *args*, it will be used as the name
47 or path of the program to execute; this will only work if the program is
48 being given no arguments.
Georg Brandl116aa622007-08-15 14:28:22 +000049
R. David Murray5973e4d2010-02-04 16:41:57 +000050 .. note::
51
52 :meth:`shlex.split` can be useful when determining the correct
53 tokenization for *args*, especially in complex cases::
54
55 >>> import shlex, subprocess
R. David Murray73bc75b2010-02-05 16:25:12 +000056 >>> command_line = input()
R. David Murray5973e4d2010-02-04 16:41:57 +000057 /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
58 >>> args = shlex.split(command_line)
59 >>> print(args)
60 ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
61 >>> p = subprocess.Popen(args) # Success!
62
63 Note in particular that options (such as *-input*) and arguments (such
64 as *eggs.txt*) that are separated by whitespace in the shell go in separate
65 list elements, while arguments that need quoting or backslash escaping when
66 used in the shell (such as filenames containing spaces or the *echo* command
67 shown above) are single list elements.
68
69 On Unix, with *shell=True*: If args is a string, it specifies the command
70 string to execute through the shell. This means that the string must be
71 formatted exactly as it would be when typed at the shell prompt. This
72 includes, for example, quoting or backslash escaping filenames with spaces in
73 them. If *args* is a sequence, the first item specifies the command string, and
74 any additional items will be treated as additional arguments to the shell
75 itself. That is to say, *Popen* does the equivalent of::
76
77 Popen(['/bin/sh', '-c', args[0], args[1], ...])
Georg Brandl116aa622007-08-15 14:28:22 +000078
R. David Murrayc7399d02010-11-12 00:35:31 +000079 .. warning::
80
81 Executing shell commands that incorporate unsanitized input from an
82 untrusted source makes a program vulnerable to `shell injection
83 <http://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_,
84 a serious security flaw which can result in arbitrary command execution.
85 For this reason, the use of *shell=True* is **strongly discouraged** in cases
86 where the command string is constructed from external input::
87
88 >>> from subprocess import call
89 >>> filename = input("What file would you like to display?\n")
90 What file would you like to display?
91 non_existent; rm -rf / #
92 >>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...
93
94 *shell=False* does not suffer from this vulnerability; the above Note may be
95 helpful in getting code using *shell=False* to work.
96
Eli Bendersky046a7642011-04-15 07:23:26 +030097 On Windows: the :class:`Popen` class uses CreateProcess() to execute the
98 child program, which operates on strings. If *args* is a sequence, it will
99 be converted to a string in a manner described in
100 :ref:`converting-argument-sequence`.
Georg Brandl116aa622007-08-15 14:28:22 +0000101
102 *bufsize*, if given, has the same meaning as the corresponding argument to the
103 built-in open() function: :const:`0` means unbuffered, :const:`1` means line
104 buffered, any other positive value means use a buffer of (approximately) that
105 size. A negative *bufsize* means to use the system default, which usually means
106 fully buffered. The default value for *bufsize* is :const:`0` (unbuffered).
107
Antoine Pitrou4b876202010-06-02 17:10:49 +0000108 .. note::
109
110 If you experience performance issues, it is recommended that you try to
111 enable buffering by setting *bufsize* to either -1 or a large enough
112 positive value (such as 4096).
113
Georg Brandl116aa622007-08-15 14:28:22 +0000114 The *executable* argument specifies the program to execute. It is very seldom
115 needed: Usually, the program to execute is defined by the *args* argument. If
116 ``shell=True``, the *executable* argument specifies which shell to use. On Unix,
117 the default shell is :file:`/bin/sh`. On Windows, the default shell is
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000118 specified by the :envvar:`COMSPEC` environment variable. The only reason you
119 would need to specify ``shell=True`` on Windows is where the command you
120 wish to execute is actually built in to the shell, eg ``dir``, ``copy``.
121 You don't need ``shell=True`` to run a batch file, nor to run a console-based
122 executable.
Georg Brandl116aa622007-08-15 14:28:22 +0000123
124 *stdin*, *stdout* and *stderr* specify the executed programs' standard input,
Georg Brandlaf265f42008-12-07 15:06:20 +0000125 standard output and standard error file handles, respectively. Valid values
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200126 are :data:`PIPE`, :data:`DEVNULL`, an existing file descriptor (a positive
127 integer), an existing :term:`file object`, and ``None``. :data:`PIPE`
128 indicates that a new pipe to the child should be created. :data:`DEVNULL`
129 indicates that the special file :data:`os.devnull` will be used. With ``None``,
130 no redirection will occur; the child's file handles will be inherited from
131 the parent. Additionally, *stderr* can be :data:`STDOUT`, which indicates
132 that the stderr data from the applications should be captured into the same
133 file handle as for stdout.
Georg Brandl116aa622007-08-15 14:28:22 +0000134
135 If *preexec_fn* is set to a callable object, this object will be called in the
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000136 child process just before the child is executed.
137 (Unix only)
138
139 .. warning::
140
141 The *preexec_fn* parameter is not safe to use in the presence of threads
142 in your application. The child process could deadlock before exec is
143 called.
144 If you must use it, keep it trivial! Minimize the number of libraries
145 you call into.
146
147 .. note::
148
149 If you need to modify the environment for the child use the *env*
150 parameter rather than doing it in a *preexec_fn*.
151 The *start_new_session* parameter can take the place of a previously
152 common use of *preexec_fn* to call os.setsid() in the child.
Georg Brandl116aa622007-08-15 14:28:22 +0000153
154 If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and
155 :const:`2` will be closed before the child process is executed. (Unix only).
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000156 The default varies by platform: Always true on Unix. On Windows it is
157 true when *stdin*/*stdout*/*stderr* are :const:`None`, false otherwise.
Gregory P. Smithd23047b2010-12-04 09:10:44 +0000158 On Windows, if *close_fds* is true then no handles will be inherited by the
Georg Brandl116aa622007-08-15 14:28:22 +0000159 child process. Note that on Windows, you cannot set *close_fds* to true and
160 also redirect the standard handles by setting *stdin*, *stdout* or *stderr*.
161
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000162 .. versionchanged:: 3.2
163 The default for *close_fds* was changed from :const:`False` to
164 what is described above.
165
166 *pass_fds* is an optional sequence of file descriptors to keep open
167 between the parent and child. Providing any *pass_fds* forces
168 *close_fds* to be :const:`True`. (Unix only)
169
170 .. versionadded:: 3.2
171 The *pass_fds* parameter was added.
Georg Brandl116aa622007-08-15 14:28:22 +0000172
173 If *cwd* is not ``None``, the child's current directory will be changed to *cwd*
174 before it is executed. Note that this directory is not considered when
175 searching the executable, so you can't specify the program's path relative to
176 *cwd*.
177
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000178 If *restore_signals* is True (the default) all signals that Python has set to
179 SIG_IGN are restored to SIG_DFL in the child process before the exec.
180 Currently this includes the SIGPIPE, SIGXFZ and SIGXFSZ signals.
181 (Unix only)
182
183 .. versionchanged:: 3.2
184 *restore_signals* was added.
185
186 If *start_new_session* is True the setsid() system call will be made in the
187 child process prior to the execution of the subprocess. (Unix only)
188
189 .. versionchanged:: 3.2
190 *start_new_session* was added.
191
Christian Heimesa342c012008-04-20 21:01:16 +0000192 If *env* is not ``None``, it must be a mapping that defines the environment
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000193 variables for the new process; these are used instead of the default
194 behavior of inheriting the current process' environment.
Georg Brandl116aa622007-08-15 14:28:22 +0000195
R. David Murray1055e892009-04-16 18:15:32 +0000196 .. note::
R. David Murrayf4ac1492009-04-15 22:35:15 +0000197
Georg Brandl2708f3a2009-12-20 14:38:23 +0000198 If specified, *env* must provide any variables required for the program to
199 execute. On Windows, in order to run a `side-by-side assembly`_ the
200 specified *env* **must** include a valid :envvar:`SystemRoot`.
R. David Murrayf4ac1492009-04-15 22:35:15 +0000201
R. David Murray1055e892009-04-16 18:15:32 +0000202 .. _side-by-side assembly: http://en.wikipedia.org/wiki/Side-by-Side_Assembly
203
Georg Brandl116aa622007-08-15 14:28:22 +0000204 If *universal_newlines* is :const:`True`, the file objects stdout and stderr are
205 opened as text files, but lines may be terminated by any of ``'\n'``, the Unix
Georg Brandlc575c902008-09-13 17:46:05 +0000206 end-of-line convention, ``'\r'``, the old Macintosh convention or ``'\r\n'``, the
Georg Brandl116aa622007-08-15 14:28:22 +0000207 Windows convention. All of these external representations are seen as ``'\n'``
208 by the Python program.
209
210 .. note::
211
Georg Brandl7f01a132009-09-16 15:58:14 +0000212 This feature is only available if Python is built with universal newline
213 support (the default). Also, the newlines attribute of the file objects
214 :attr:`stdout`, :attr:`stdin` and :attr:`stderr` are not updated by the
215 :meth:`communicate` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000216
Brian Curtine6242d72011-04-29 22:17:51 -0500217 If given, *startupinfo* will be a :class:`STARTUPINFO` object, which is
218 passed to the underlying ``CreateProcess`` function.
Brian Curtin30401932011-04-29 22:20:57 -0500219 *creationflags*, if given, can be :data:`CREATE_NEW_CONSOLE` or
220 :data:`CREATE_NEW_PROCESS_GROUP`. (Windows only)
Georg Brandl116aa622007-08-15 14:28:22 +0000221
Gregory P. Smith6b657452011-05-11 21:42:08 -0700222 Popen objects are supported as context managers via the :keyword:`with` statement:
223 on exit, standard file descriptors are closed, and the process is waited for.
Brian Curtin79cdb662010-12-03 02:46:02 +0000224 ::
225
226 with Popen(["ifconfig"], stdout=PIPE) as proc:
227 log.write(proc.stdout.read())
228
229 .. versionchanged:: 3.2
230 Added context manager support.
231
Georg Brandl116aa622007-08-15 14:28:22 +0000232
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200233.. data:: DEVNULL
234
235 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
236 to :class:`Popen` and indicates that the special file :data:`os.devnull`
237 will be used.
238
239 .. versionadded:: 3.3
240
241
Georg Brandlaf265f42008-12-07 15:06:20 +0000242.. data:: PIPE
243
244 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
245 to :class:`Popen` and indicates that a pipe to the standard stream should be
246 opened.
247
248
249.. data:: STDOUT
250
251 Special value that can be used as the *stderr* argument to :class:`Popen` and
252 indicates that standard error should go into the same handle as standard
253 output.
Georg Brandl48310cd2009-01-03 21:18:54 +0000254
Georg Brandlaf265f42008-12-07 15:06:20 +0000255
Georg Brandl116aa622007-08-15 14:28:22 +0000256Convenience Functions
257^^^^^^^^^^^^^^^^^^^^^
258
Ezio Melotti8dfcab02011-04-19 23:15:13 +0300259This module also defines the following shortcut functions:
Georg Brandl116aa622007-08-15 14:28:22 +0000260
261
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400262.. function:: call(*popenargs, timeout=None, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000263
264 Run command with arguments. Wait for command to complete, then return the
265 :attr:`returncode` attribute.
266
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400267 The arguments are the same as for the :class:`Popen` constructor, with the
268 exception of the *timeout* argument, which is given to :meth:`Popen.wait`.
269 Example::
Georg Brandl116aa622007-08-15 14:28:22 +0000270
Georg Brandl2708f3a2009-12-20 14:38:23 +0000271 >>> retcode = subprocess.call(["ls", "-l"])
Georg Brandl116aa622007-08-15 14:28:22 +0000272
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400273 If the timeout expires, the child process will be killed and then waited for
274 again. The :exc:`TimeoutExpired` exception will be re-raised after the child
275 process has terminated.
276
Philip Jenveyab7481a2009-05-22 05:46:35 +0000277 .. warning::
278
Philip Jenveyb0896842009-12-03 02:29:36 +0000279 Like :meth:`Popen.wait`, this will deadlock when using
280 ``stdout=PIPE`` and/or ``stderr=PIPE`` and the child process
281 generates enough output to a pipe such that it blocks waiting
282 for the OS pipe buffer to accept more data.
Philip Jenveyab7481a2009-05-22 05:46:35 +0000283
Reid Kleckner28f13032011-03-14 12:36:53 -0400284 .. versionchanged:: 3.3
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400285 *timeout* was added.
Georg Brandl116aa622007-08-15 14:28:22 +0000286
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400287
288.. function:: check_call(*popenargs, timeout=None, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000289
290 Run command with arguments. Wait for command to complete. If the exit code was
Benjamin Petersone5384b02008-10-04 22:00:42 +0000291 zero then return, otherwise raise :exc:`CalledProcessError`. The
Georg Brandl116aa622007-08-15 14:28:22 +0000292 :exc:`CalledProcessError` object will have the return code in the
293 :attr:`returncode` attribute.
294
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400295 The arguments are the same as for the :func:`call` function. Example::
Georg Brandl116aa622007-08-15 14:28:22 +0000296
Georg Brandl2708f3a2009-12-20 14:38:23 +0000297 >>> subprocess.check_call(["ls", "-l"])
298 0
Georg Brandl116aa622007-08-15 14:28:22 +0000299
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400300 As in the :func:`call` function, if the timeout expires, the child process
301 will be killed and the wait retried. The :exc:`TimeoutExpired` exception
302 will be re-raised after the child process has terminated.
303
Philip Jenveyab7481a2009-05-22 05:46:35 +0000304 .. warning::
305
306 See the warning for :func:`call`.
307
Reid Kleckner28f13032011-03-14 12:36:53 -0400308 .. versionchanged:: 3.3
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400309 *timeout* was added.
Georg Brandl116aa622007-08-15 14:28:22 +0000310
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400311
312.. function:: check_output(*popenargs, timeout=None, **kwargs)
Georg Brandlf9734072008-12-07 15:30:06 +0000313
Gregory P. Smitha454ef62011-05-22 22:29:49 -0700314 Run command with arguments and return its output as a bytes object.
Georg Brandlf9734072008-12-07 15:30:06 +0000315
Benjamin Petersonaa069002009-01-23 03:26:36 +0000316 If the exit code was non-zero it raises a :exc:`CalledProcessError`. The
317 :exc:`CalledProcessError` object will have the return code in the
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400318 :attr:`returncode` attribute and output in the :attr:`output` attribute.
Georg Brandlf9734072008-12-07 15:30:06 +0000319
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400320 The arguments are the same as for the :func:`call` function. Example::
Georg Brandlf9734072008-12-07 15:30:06 +0000321
322 >>> subprocess.check_output(["ls", "-l", "/dev/null"])
Georg Brandl2708f3a2009-12-20 14:38:23 +0000323 b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000324
325 The stdout argument is not allowed as it is used internally.
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000326 To capture standard error in the result, use ``stderr=subprocess.STDOUT``::
Georg Brandlf9734072008-12-07 15:30:06 +0000327
328 >>> subprocess.check_output(
Georg Brandl2708f3a2009-12-20 14:38:23 +0000329 ... ["/bin/sh", "-c", "ls non_existent_file; exit 0"],
330 ... stderr=subprocess.STDOUT)
331 b'ls: non_existent_file: No such file or directory\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000332
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400333 As in the :func:`call` function, if the timeout expires, the child process
334 will be killed and the wait retried. The :exc:`TimeoutExpired` exception
335 will be re-raised after the child process has terminated. The output from
336 the child process so far will be in the :attr:`output` attribute of the
337 exception.
338
Georg Brandlf9734072008-12-07 15:30:06 +0000339 .. versionadded:: 3.1
340
Reid Kleckner28f13032011-03-14 12:36:53 -0400341 .. versionchanged:: 3.3
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400342 *timeout* was added.
343
Georg Brandlf9734072008-12-07 15:30:06 +0000344
Brett Cannona23810f2008-05-26 19:04:21 +0000345.. function:: getstatusoutput(cmd)
Georg Brandl682d7e02010-10-06 10:26:05 +0000346
Brett Cannona23810f2008-05-26 19:04:21 +0000347 Return ``(status, output)`` of executing *cmd* in a shell.
348
349 Execute the string *cmd* in a shell with :func:`os.popen` and return a 2-tuple
350 ``(status, output)``. *cmd* is actually run as ``{ cmd ; } 2>&1``, so that the
351 returned output will contain output or error messages. A trailing newline is
352 stripped from the output. The exit status for the command can be interpreted
Georg Brandl60203b42010-10-06 10:11:56 +0000353 according to the rules for the C function :c:func:`wait`. Example::
Brett Cannona23810f2008-05-26 19:04:21 +0000354
Brett Cannona23810f2008-05-26 19:04:21 +0000355 >>> subprocess.getstatusoutput('ls /bin/ls')
356 (0, '/bin/ls')
357 >>> subprocess.getstatusoutput('cat /bin/junk')
358 (256, 'cat: /bin/junk: No such file or directory')
359 >>> subprocess.getstatusoutput('/bin/junk')
360 (256, 'sh: /bin/junk: not found')
361
Georg Brandl7d418902008-12-27 19:08:11 +0000362 Availability: UNIX.
363
Brett Cannona23810f2008-05-26 19:04:21 +0000364
365.. function:: getoutput(cmd)
Georg Brandl682d7e02010-10-06 10:26:05 +0000366
Georg Brandlf9734072008-12-07 15:30:06 +0000367 Return output (stdout and stderr) of executing *cmd* in a shell.
Brett Cannona23810f2008-05-26 19:04:21 +0000368
369 Like :func:`getstatusoutput`, except the exit status is ignored and the return
370 value is a string containing the command's output. Example::
371
Brett Cannona23810f2008-05-26 19:04:21 +0000372 >>> subprocess.getoutput('ls /bin/ls')
373 '/bin/ls'
374
Georg Brandl7d418902008-12-27 19:08:11 +0000375 Availability: UNIX.
376
Brett Cannona23810f2008-05-26 19:04:21 +0000377
Georg Brandl116aa622007-08-15 14:28:22 +0000378Exceptions
379^^^^^^^^^^
380
381Exceptions raised in the child process, before the new program has started to
382execute, will be re-raised in the parent. Additionally, the exception object
383will have one extra attribute called :attr:`child_traceback`, which is a string
Georg Brandl81675612010-08-26 14:30:56 +0000384containing traceback information from the child's point of view.
Georg Brandl116aa622007-08-15 14:28:22 +0000385
386The most common exception raised is :exc:`OSError`. This occurs, for example,
387when trying to execute a non-existent file. Applications should prepare for
388:exc:`OSError` exceptions.
389
390A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid
391arguments.
392
393check_call() will raise :exc:`CalledProcessError`, if the called process returns
394a non-zero return code.
395
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400396All of the functions and methods that accept a *timeout* parameter, such as
397:func:`call` and :meth:`Popen.communicate` will raise :exc:`TimeoutExpired` if
398the timeout expires before the process exits.
399
Ronald Oussorenc1577902011-03-16 10:03:10 -0400400Exceptions defined in this module all inherit from :exc:`SubprocessError`.
Gregory P. Smith54d412e2011-03-14 14:08:43 -0400401
402 .. versionadded:: 3.3
403 The :exc:`SubprocessError` base class was added.
404
Georg Brandl116aa622007-08-15 14:28:22 +0000405
406Security
407^^^^^^^^
408
409Unlike some other popen functions, this implementation will never call /bin/sh
410implicitly. This means that all characters, including shell metacharacters, can
411safely be passed to child processes.
412
413
414Popen Objects
415-------------
416
417Instances of the :class:`Popen` class have the following methods:
418
419
420.. method:: Popen.poll()
421
Christian Heimes7f044312008-01-06 17:05:40 +0000422 Check if child process has terminated. Set and return :attr:`returncode`
423 attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000424
425
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400426.. method:: Popen.wait(timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000427
Christian Heimes7f044312008-01-06 17:05:40 +0000428 Wait for child process to terminate. Set and return :attr:`returncode`
429 attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000430
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400431 If the process does not terminate after *timeout* seconds, raise a
432 :exc:`TimeoutExpired` exception. It is safe to catch this exception and
433 retry the wait.
434
Georg Brandl734e2682008-08-12 08:18:18 +0000435 .. warning::
436
Philip Jenveyb0896842009-12-03 02:29:36 +0000437 This will deadlock when using ``stdout=PIPE`` and/or
438 ``stderr=PIPE`` and the child process generates enough output to
439 a pipe such that it blocks waiting for the OS pipe buffer to
440 accept more data. Use :meth:`communicate` to avoid that.
Georg Brandl734e2682008-08-12 08:18:18 +0000441
Reid Kleckner28f13032011-03-14 12:36:53 -0400442 .. versionchanged:: 3.3
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400443 *timeout* was added.
Georg Brandl116aa622007-08-15 14:28:22 +0000444
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400445
446.. method:: Popen.communicate(input=None, timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000447
448 Interact with process: Send data to stdin. Read data from stdout and stderr,
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400449 until end-of-file is reached. Wait for process to terminate. The optional
Gregory P. Smitha454ef62011-05-22 22:29:49 -0700450 *input* argument should be data to be sent to the child process, or
451 ``None``, if no data should be sent to the child. The type of *input*
452 must be bytes or, if *universal_newlines* was ``True``, a string.
Georg Brandl116aa622007-08-15 14:28:22 +0000453
Georg Brandlaf265f42008-12-07 15:06:20 +0000454 :meth:`communicate` returns a tuple ``(stdoutdata, stderrdata)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000455
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000456 Note that if you want to send data to the process's stdin, you need to create
457 the Popen object with ``stdin=PIPE``. Similarly, to get anything other than
458 ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or
459 ``stderr=PIPE`` too.
460
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400461 If the process does not terminate after *timeout* seconds, a
462 :exc:`TimeoutExpired` exception will be raised. Catching this exception and
463 retrying communication will not lose any output.
464
465 The child process is not killed if the timeout expires, so in order to
466 cleanup properly a well-behaved application should kill the child process and
467 finish communication::
468
469 proc = subprocess.Popen(...)
470 try:
471 outs, errs = proc.communicate(timeout=15)
472 except TimeoutExpired:
473 proc.kill()
474 outs, errs = proc.communicate()
475
Christian Heimes7f044312008-01-06 17:05:40 +0000476 .. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000477
Christian Heimes7f044312008-01-06 17:05:40 +0000478 The data read is buffered in memory, so do not use this method if the data
479 size is large or unlimited.
480
Reid Kleckner28f13032011-03-14 12:36:53 -0400481 .. versionchanged:: 3.3
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400482 *timeout* was added.
483
Georg Brandl116aa622007-08-15 14:28:22 +0000484
Christian Heimesa342c012008-04-20 21:01:16 +0000485.. method:: Popen.send_signal(signal)
486
487 Sends the signal *signal* to the child.
488
489 .. note::
490
Brian Curtineb24d742010-04-12 17:16:38 +0000491 On Windows, SIGTERM is an alias for :meth:`terminate`. CTRL_C_EVENT and
Senthil Kumaran916bd382010-10-15 12:55:19 +0000492 CTRL_BREAK_EVENT can be sent to processes started with a *creationflags*
Brian Curtineb24d742010-04-12 17:16:38 +0000493 parameter which includes `CREATE_NEW_PROCESS_GROUP`.
Christian Heimesa342c012008-04-20 21:01:16 +0000494
Christian Heimesa342c012008-04-20 21:01:16 +0000495
496.. method:: Popen.terminate()
497
498 Stop the child. On Posix OSs the method sends SIGTERM to the
Georg Brandl60203b42010-10-06 10:11:56 +0000499 child. On Windows the Win32 API function :c:func:`TerminateProcess` is called
Christian Heimesa342c012008-04-20 21:01:16 +0000500 to stop the child.
501
Christian Heimesa342c012008-04-20 21:01:16 +0000502
503.. method:: Popen.kill()
504
505 Kills the child. On Posix OSs the function sends SIGKILL to the child.
506 On Windows :meth:`kill` is an alias for :meth:`terminate`.
507
Christian Heimesa342c012008-04-20 21:01:16 +0000508
Georg Brandl116aa622007-08-15 14:28:22 +0000509The following attributes are also available:
510
Georg Brandl734e2682008-08-12 08:18:18 +0000511.. warning::
512
Georg Brandle720c0a2009-04-27 16:20:50 +0000513 Use :meth:`communicate` rather than :attr:`.stdin.write <stdin>`,
514 :attr:`.stdout.read <stdout>` or :attr:`.stderr.read <stderr>` to avoid
515 deadlocks due to any of the other OS pipe buffers filling up and blocking the
516 child process.
Georg Brandl734e2682008-08-12 08:18:18 +0000517
518
Georg Brandl116aa622007-08-15 14:28:22 +0000519.. attribute:: Popen.stdin
520
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000521 If the *stdin* argument was :data:`PIPE`, this attribute is a :term:`file
522 object` that provides input to the child process. Otherwise, it is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000523
524
525.. attribute:: Popen.stdout
526
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000527 If the *stdout* argument was :data:`PIPE`, this attribute is a :term:`file
528 object` that provides output from the child process. Otherwise, it is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000529
530
531.. attribute:: Popen.stderr
532
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000533 If the *stderr* argument was :data:`PIPE`, this attribute is a :term:`file
534 object` that provides error output from the child process. Otherwise, it is
Georg Brandlaf265f42008-12-07 15:06:20 +0000535 ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000536
537
538.. attribute:: Popen.pid
539
540 The process ID of the child process.
541
Georg Brandl58bfdca2010-03-21 09:50:49 +0000542 Note that if you set the *shell* argument to ``True``, this is the process ID
543 of the spawned shell.
544
Georg Brandl116aa622007-08-15 14:28:22 +0000545
546.. attribute:: Popen.returncode
547
Christian Heimes7f044312008-01-06 17:05:40 +0000548 The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly
549 by :meth:`communicate`). A ``None`` value indicates that the process
550 hasn't terminated yet.
Georg Brandl48310cd2009-01-03 21:18:54 +0000551
Christian Heimes7f044312008-01-06 17:05:40 +0000552 A negative value ``-N`` indicates that the child was terminated by signal
553 ``N`` (Unix only).
Georg Brandl116aa622007-08-15 14:28:22 +0000554
555
Brian Curtine6242d72011-04-29 22:17:51 -0500556Windows Popen Helpers
557---------------------
558
559The :class:`STARTUPINFO` class and following constants are only available
560on Windows.
561
562.. class:: STARTUPINFO()
Brian Curtin73365dd2011-04-29 22:18:33 -0500563
Brian Curtine6242d72011-04-29 22:17:51 -0500564 Partial support of the Windows
565 `STARTUPINFO <http://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx>`__
566 structure is used for :class:`Popen` creation.
567
568 .. attribute:: dwFlags
569
570 A bit field that determines whether certain :class:`STARTUPINFO` members
571 are used when the process creates a window. ::
572
573 si = subprocess.STARTUPINFO()
574 si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
575
576 .. attribute:: hStdInput
577
578 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this member is
579 the standard input handle for the process. If :data:`STARTF_USESTDHANDLES`
580 is not specified, the default for standard input is the keyboard buffer.
581
582 .. attribute:: hStdOutput
583
584 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this member is
585 the standard output handle for the process. Otherwise, this member is
586 ignored and the default for standard output is the console window's
587 buffer.
588
589 .. attribute:: hStdError
590
591 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this member is
592 the standard error handle for the process. Otherwise, this member is
593 ignored and the default for standard error is the console window's buffer.
594
595 .. attribute:: wShowWindow
596
597 If :attr:`dwFlags` specifies :data:`STARTF_USESHOWWINDOW`, this member
598 can be any of the values that can be specified in the ``nCmdShow``
599 parameter for the
600 `ShowWindow <http://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx>`__
601 function, except for ``SW_SHOWDEFAULT``. Otherwise, this member is
602 ignored.
Brian Curtin73365dd2011-04-29 22:18:33 -0500603
Brian Curtine6242d72011-04-29 22:17:51 -0500604 :data:`SW_HIDE` is provided for this attribute. It is used when
605 :class:`Popen` is called with ``shell=True``.
606
607
608Constants
609^^^^^^^^^
610
611The :mod:`subprocess` module exposes the following constants.
612
613.. data:: STD_INPUT_HANDLE
614
615 The standard input device. Initially, this is the console input buffer,
616 ``CONIN$``.
617
618.. data:: STD_OUTPUT_HANDLE
619
620 The standard output device. Initially, this is the active console screen
621 buffer, ``CONOUT$``.
622
623.. data:: STD_ERROR_HANDLE
624
625 The standard error device. Initially, this is the active console screen
626 buffer, ``CONOUT$``.
627
628.. data:: SW_HIDE
629
630 Hides the window. Another window will be activated.
631
632.. data:: STARTF_USESTDHANDLES
633
634 Specifies that the :attr:`STARTUPINFO.hStdInput`,
635 :attr:`STARTUPINFO.hStdOutput`, and :attr:`STARTUPINFO.hStdError` members
636 contain additional information.
637
638.. data:: STARTF_USESHOWWINDOW
639
640 Specifies that the :attr:`STARTUPINFO.wShowWindow` member contains
641 additional information.
642
643.. data:: CREATE_NEW_CONSOLE
644
645 The new process has a new console, instead of inheriting its parent's
646 console (the default).
Brian Curtin73365dd2011-04-29 22:18:33 -0500647
Brian Curtine6242d72011-04-29 22:17:51 -0500648 This flag is always set when :class:`Popen` is created with ``shell=True``.
649
Brian Curtin30401932011-04-29 22:20:57 -0500650.. data:: CREATE_NEW_PROCESS_GROUP
651
652 A :class:`Popen` ``creationflags`` parameter to specify that a new process
653 group will be created. This flag is necessary for using :func:`os.kill`
654 on the subprocess.
655
656 This flag is ignored if :data:`CREATE_NEW_CONSOLE` is specified.
657
Brian Curtine6242d72011-04-29 22:17:51 -0500658
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000659.. _subprocess-replacements:
660
Georg Brandl116aa622007-08-15 14:28:22 +0000661Replacing Older Functions with the subprocess Module
662----------------------------------------------------
663
664In this section, "a ==> b" means that b can be used as a replacement for a.
665
666.. note::
667
668 All functions in this section fail (more or less) silently if the executed
669 program cannot be found; this module raises an :exc:`OSError` exception.
670
671In the following examples, we assume that the subprocess module is imported with
672"from subprocess import \*".
673
674
675Replacing /bin/sh shell backquote
676^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
677
678::
679
680 output=`mycmd myarg`
681 ==>
682 output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
683
684
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000685Replacing shell pipeline
686^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000687
688::
689
690 output=`dmesg | grep hda`
691 ==>
692 p1 = Popen(["dmesg"], stdout=PIPE)
693 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Gregory P. Smithe09d2f12011-02-05 21:47:25 +0000694 p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
Georg Brandl116aa622007-08-15 14:28:22 +0000695 output = p2.communicate()[0]
696
Gregory P. Smithe09d2f12011-02-05 21:47:25 +0000697The p1.stdout.close() call after starting the p2 is important in order for p1
698to receive a SIGPIPE if p2 exits before p1.
Georg Brandl116aa622007-08-15 14:28:22 +0000699
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000700Replacing :func:`os.system`
701^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000702
703::
704
705 sts = os.system("mycmd" + " myarg")
706 ==>
707 p = Popen("mycmd" + " myarg", shell=True)
Alexandre Vassalottie52e3782009-07-17 09:18:18 +0000708 sts = os.waitpid(p.pid, 0)[1]
Georg Brandl116aa622007-08-15 14:28:22 +0000709
710Notes:
711
712* Calling the program through the shell is usually not required.
713
714* It's easier to look at the :attr:`returncode` attribute than the exit status.
715
716A more realistic example would look like this::
717
718 try:
719 retcode = call("mycmd" + " myarg", shell=True)
720 if retcode < 0:
Collin Winterc79461b2007-09-01 23:34:30 +0000721 print("Child was terminated by signal", -retcode, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000722 else:
Collin Winterc79461b2007-09-01 23:34:30 +0000723 print("Child returned", retcode, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000724 except OSError as e:
Collin Winterc79461b2007-09-01 23:34:30 +0000725 print("Execution failed:", e, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000726
727
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000728Replacing the :func:`os.spawn <os.spawnl>` family
729^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000730
731P_NOWAIT example::
732
733 pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
734 ==>
735 pid = Popen(["/bin/mycmd", "myarg"]).pid
736
737P_WAIT example::
738
739 retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
740 ==>
741 retcode = call(["/bin/mycmd", "myarg"])
742
743Vector example::
744
745 os.spawnvp(os.P_NOWAIT, path, args)
746 ==>
747 Popen([path] + args[1:])
748
749Environment example::
750
751 os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
752 ==>
753 Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
754
755
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000756
757Replacing :func:`os.popen`, :func:`os.popen2`, :func:`os.popen3`
758^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000759
760::
761
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000762 (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
Georg Brandl116aa622007-08-15 14:28:22 +0000763 ==>
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000764 p = Popen(cmd, shell=True, bufsize=bufsize,
765 stdin=PIPE, stdout=PIPE, close_fds=True)
766 (child_stdin, child_stdout) = (p.stdin, p.stdout)
Georg Brandl116aa622007-08-15 14:28:22 +0000767
768::
769
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000770 (child_stdin,
771 child_stdout,
772 child_stderr) = os.popen3(cmd, mode, bufsize)
Georg Brandl116aa622007-08-15 14:28:22 +0000773 ==>
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000774 p = Popen(cmd, shell=True, bufsize=bufsize,
775 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
776 (child_stdin,
777 child_stdout,
778 child_stderr) = (p.stdin, p.stdout, p.stderr)
779
780::
781
782 (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
783 ==>
784 p = Popen(cmd, shell=True, bufsize=bufsize,
785 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
786 (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
787
788Return code handling translates as follows::
789
790 pipe = os.popen(cmd, 'w')
791 ...
792 rc = pipe.close()
Stefan Krahfc9e08d2010-07-14 10:16:11 +0000793 if rc is not None and rc >> 8:
Ezio Melotti985e24d2009-09-13 07:54:02 +0000794 print("There were some errors")
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000795 ==>
796 process = Popen(cmd, 'w', stdin=PIPE)
797 ...
798 process.stdin.close()
799 if process.wait() != 0:
Ezio Melotti985e24d2009-09-13 07:54:02 +0000800 print("There were some errors")
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000801
802
803Replacing functions from the :mod:`popen2` module
804^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
805
806.. note::
807
808 If the cmd argument to popen2 functions is a string, the command is executed
809 through /bin/sh. If it is a list, the command is directly executed.
810
811::
812
813 (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
814 ==>
815 p = Popen(["somestring"], shell=True, bufsize=bufsize,
816 stdin=PIPE, stdout=PIPE, close_fds=True)
817 (child_stdout, child_stdin) = (p.stdout, p.stdin)
818
819::
820
821 (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
822 ==>
823 p = Popen(["mycmd", "myarg"], bufsize=bufsize,
824 stdin=PIPE, stdout=PIPE, close_fds=True)
825 (child_stdout, child_stdin) = (p.stdout, p.stdin)
826
827:class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as
828:class:`subprocess.Popen`, except that:
829
830* :class:`Popen` raises an exception if the execution fails.
831
832* the *capturestderr* argument is replaced with the *stderr* argument.
833
834* ``stdin=PIPE`` and ``stdout=PIPE`` must be specified.
835
836* popen2 closes all file descriptors by default, but you have to specify
Gregory P. Smithf5604852010-12-13 06:45:02 +0000837 ``close_fds=True`` with :class:`Popen` to guarantee this behavior on
838 all platforms or past Python versions.
Eli Bendersky046a7642011-04-15 07:23:26 +0300839
840Notes
841-----
842
843.. _converting-argument-sequence:
844
845Converting an argument sequence to a string on Windows
846^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
847
848On Windows, an *args* sequence is converted to a string that can be parsed
849using the following rules (which correspond to the rules used by the MS C
850runtime):
851
8521. Arguments are delimited by white space, which is either a
853 space or a tab.
854
8552. A string surrounded by double quotation marks is
856 interpreted as a single argument, regardless of white space
857 contained within. A quoted string can be embedded in an
858 argument.
859
8603. A double quotation mark preceded by a backslash is
861 interpreted as a literal double quotation mark.
862
8634. Backslashes are interpreted literally, unless they
864 immediately precede a double quotation mark.
865
8665. If backslashes immediately precede a double quotation mark,
867 every pair of backslashes is interpreted as a literal
868 backslash. If the number of backslashes is odd, the last
869 backslash escapes the next double quotation mark as
870 described in rule 3.
871
Eli Benderskyd2112312011-04-15 07:26:28 +0300872