blob: 2c7613027bd0bc45b952b5b63129fe446efb4a18 [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
Éric Araujo9bce3112011-07-27 18:29:31 +020095 helpful in getting code using *shell=False* to work. See also
96 :func:`shlex.quote` for a function useful to quote filenames and commands.
R. David Murrayc7399d02010-11-12 00:35:31 +000097
Eli Bendersky046a7642011-04-15 07:23:26 +030098 On Windows: the :class:`Popen` class uses CreateProcess() to execute the
99 child program, which operates on strings. If *args* is a sequence, it will
100 be converted to a string in a manner described in
101 :ref:`converting-argument-sequence`.
Georg Brandl116aa622007-08-15 14:28:22 +0000102
103 *bufsize*, if given, has the same meaning as the corresponding argument to the
104 built-in open() function: :const:`0` means unbuffered, :const:`1` means line
105 buffered, any other positive value means use a buffer of (approximately) that
106 size. A negative *bufsize* means to use the system default, which usually means
107 fully buffered. The default value for *bufsize* is :const:`0` (unbuffered).
108
Antoine Pitrou4b876202010-06-02 17:10:49 +0000109 .. note::
110
111 If you experience performance issues, it is recommended that you try to
112 enable buffering by setting *bufsize* to either -1 or a large enough
113 positive value (such as 4096).
114
Georg Brandl116aa622007-08-15 14:28:22 +0000115 The *executable* argument specifies the program to execute. It is very seldom
116 needed: Usually, the program to execute is defined by the *args* argument. If
117 ``shell=True``, the *executable* argument specifies which shell to use. On Unix,
118 the default shell is :file:`/bin/sh`. On Windows, the default shell is
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000119 specified by the :envvar:`COMSPEC` environment variable. The only reason you
120 would need to specify ``shell=True`` on Windows is where the command you
121 wish to execute is actually built in to the shell, eg ``dir``, ``copy``.
122 You don't need ``shell=True`` to run a batch file, nor to run a console-based
123 executable.
Georg Brandl116aa622007-08-15 14:28:22 +0000124
125 *stdin*, *stdout* and *stderr* specify the executed programs' standard input,
Georg Brandlaf265f42008-12-07 15:06:20 +0000126 standard output and standard error file handles, respectively. Valid values
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200127 are :data:`PIPE`, :data:`DEVNULL`, an existing file descriptor (a positive
128 integer), an existing :term:`file object`, and ``None``. :data:`PIPE`
129 indicates that a new pipe to the child should be created. :data:`DEVNULL`
130 indicates that the special file :data:`os.devnull` will be used. With ``None``,
131 no redirection will occur; the child's file handles will be inherited from
132 the parent. Additionally, *stderr* can be :data:`STDOUT`, which indicates
133 that the stderr data from the applications should be captured into the same
134 file handle as for stdout.
Georg Brandl116aa622007-08-15 14:28:22 +0000135
136 If *preexec_fn* is set to a callable object, this object will be called in the
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000137 child process just before the child is executed.
138 (Unix only)
139
140 .. warning::
141
142 The *preexec_fn* parameter is not safe to use in the presence of threads
143 in your application. The child process could deadlock before exec is
144 called.
145 If you must use it, keep it trivial! Minimize the number of libraries
146 you call into.
147
148 .. note::
149
150 If you need to modify the environment for the child use the *env*
151 parameter rather than doing it in a *preexec_fn*.
152 The *start_new_session* parameter can take the place of a previously
153 common use of *preexec_fn* to call os.setsid() in the child.
Georg Brandl116aa622007-08-15 14:28:22 +0000154
155 If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and
156 :const:`2` will be closed before the child process is executed. (Unix only).
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000157 The default varies by platform: Always true on Unix. On Windows it is
158 true when *stdin*/*stdout*/*stderr* are :const:`None`, false otherwise.
Gregory P. Smithd23047b2010-12-04 09:10:44 +0000159 On Windows, if *close_fds* is true then no handles will be inherited by the
Georg Brandl116aa622007-08-15 14:28:22 +0000160 child process. Note that on Windows, you cannot set *close_fds* to true and
161 also redirect the standard handles by setting *stdin*, *stdout* or *stderr*.
162
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000163 .. versionchanged:: 3.2
164 The default for *close_fds* was changed from :const:`False` to
165 what is described above.
166
167 *pass_fds* is an optional sequence of file descriptors to keep open
168 between the parent and child. Providing any *pass_fds* forces
169 *close_fds* to be :const:`True`. (Unix only)
170
171 .. versionadded:: 3.2
172 The *pass_fds* parameter was added.
Georg Brandl116aa622007-08-15 14:28:22 +0000173
174 If *cwd* is not ``None``, the child's current directory will be changed to *cwd*
175 before it is executed. Note that this directory is not considered when
176 searching the executable, so you can't specify the program's path relative to
177 *cwd*.
178
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000179 If *restore_signals* is True (the default) all signals that Python has set to
180 SIG_IGN are restored to SIG_DFL in the child process before the exec.
181 Currently this includes the SIGPIPE, SIGXFZ and SIGXFSZ signals.
182 (Unix only)
183
184 .. versionchanged:: 3.2
185 *restore_signals* was added.
186
187 If *start_new_session* is True the setsid() system call will be made in the
188 child process prior to the execution of the subprocess. (Unix only)
189
190 .. versionchanged:: 3.2
191 *start_new_session* was added.
192
Christian Heimesa342c012008-04-20 21:01:16 +0000193 If *env* is not ``None``, it must be a mapping that defines the environment
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000194 variables for the new process; these are used instead of the default
195 behavior of inheriting the current process' environment.
Georg Brandl116aa622007-08-15 14:28:22 +0000196
R. David Murray1055e892009-04-16 18:15:32 +0000197 .. note::
R. David Murrayf4ac1492009-04-15 22:35:15 +0000198
Georg Brandl2708f3a2009-12-20 14:38:23 +0000199 If specified, *env* must provide any variables required for the program to
200 execute. On Windows, in order to run a `side-by-side assembly`_ the
201 specified *env* **must** include a valid :envvar:`SystemRoot`.
R. David Murrayf4ac1492009-04-15 22:35:15 +0000202
R. David Murray1055e892009-04-16 18:15:32 +0000203 .. _side-by-side assembly: http://en.wikipedia.org/wiki/Side-by-Side_Assembly
204
Georg Brandl116aa622007-08-15 14:28:22 +0000205 If *universal_newlines* is :const:`True`, the file objects stdout and stderr are
206 opened as text files, but lines may be terminated by any of ``'\n'``, the Unix
Georg Brandlc575c902008-09-13 17:46:05 +0000207 end-of-line convention, ``'\r'``, the old Macintosh convention or ``'\r\n'``, the
Georg Brandl116aa622007-08-15 14:28:22 +0000208 Windows convention. All of these external representations are seen as ``'\n'``
209 by the Python program.
210
211 .. note::
212
Georg Brandl7f01a132009-09-16 15:58:14 +0000213 This feature is only available if Python is built with universal newline
214 support (the default). Also, the newlines attribute of the file objects
215 :attr:`stdout`, :attr:`stdin` and :attr:`stderr` are not updated by the
216 :meth:`communicate` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000217
Brian Curtine6242d72011-04-29 22:17:51 -0500218 If given, *startupinfo* will be a :class:`STARTUPINFO` object, which is
219 passed to the underlying ``CreateProcess`` function.
Brian Curtin30401932011-04-29 22:20:57 -0500220 *creationflags*, if given, can be :data:`CREATE_NEW_CONSOLE` or
221 :data:`CREATE_NEW_PROCESS_GROUP`. (Windows only)
Georg Brandl116aa622007-08-15 14:28:22 +0000222
Gregory P. Smith6b657452011-05-11 21:42:08 -0700223 Popen objects are supported as context managers via the :keyword:`with` statement:
224 on exit, standard file descriptors are closed, and the process is waited for.
Brian Curtin79cdb662010-12-03 02:46:02 +0000225 ::
226
227 with Popen(["ifconfig"], stdout=PIPE) as proc:
228 log.write(proc.stdout.read())
229
230 .. versionchanged:: 3.2
231 Added context manager support.
232
Georg Brandl116aa622007-08-15 14:28:22 +0000233
Ross Lagerwallba102ec2011-03-16 18:40:25 +0200234.. data:: DEVNULL
235
236 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
237 to :class:`Popen` and indicates that the special file :data:`os.devnull`
238 will be used.
239
240 .. versionadded:: 3.3
241
242
Georg Brandlaf265f42008-12-07 15:06:20 +0000243.. data:: PIPE
244
245 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
246 to :class:`Popen` and indicates that a pipe to the standard stream should be
247 opened.
248
249
250.. data:: STDOUT
251
252 Special value that can be used as the *stderr* argument to :class:`Popen` and
253 indicates that standard error should go into the same handle as standard
254 output.
Georg Brandl48310cd2009-01-03 21:18:54 +0000255
Georg Brandlaf265f42008-12-07 15:06:20 +0000256
Georg Brandl116aa622007-08-15 14:28:22 +0000257Convenience Functions
258^^^^^^^^^^^^^^^^^^^^^
259
Ezio Melotti8dfcab02011-04-19 23:15:13 +0300260This module also defines the following shortcut functions:
Georg Brandl116aa622007-08-15 14:28:22 +0000261
262
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400263.. function:: call(*popenargs, timeout=None, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000264
265 Run command with arguments. Wait for command to complete, then return the
266 :attr:`returncode` attribute.
267
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400268 The arguments are the same as for the :class:`Popen` constructor, with the
269 exception of the *timeout* argument, which is given to :meth:`Popen.wait`.
270 Example::
Georg Brandl116aa622007-08-15 14:28:22 +0000271
Georg Brandl2708f3a2009-12-20 14:38:23 +0000272 >>> retcode = subprocess.call(["ls", "-l"])
Georg Brandl116aa622007-08-15 14:28:22 +0000273
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400274 If the timeout expires, the child process will be killed and then waited for
275 again. The :exc:`TimeoutExpired` exception will be re-raised after the child
276 process has terminated.
277
Philip Jenveyab7481a2009-05-22 05:46:35 +0000278 .. warning::
279
Philip Jenveyb0896842009-12-03 02:29:36 +0000280 Like :meth:`Popen.wait`, this will deadlock when using
281 ``stdout=PIPE`` and/or ``stderr=PIPE`` and the child process
282 generates enough output to a pipe such that it blocks waiting
283 for the OS pipe buffer to accept more data.
Philip Jenveyab7481a2009-05-22 05:46:35 +0000284
Reid Kleckner28f13032011-03-14 12:36:53 -0400285 .. versionchanged:: 3.3
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400286 *timeout* was added.
Georg Brandl116aa622007-08-15 14:28:22 +0000287
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400288
289.. function:: check_call(*popenargs, timeout=None, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000290
291 Run command with arguments. Wait for command to complete. If the exit code was
Benjamin Petersone5384b02008-10-04 22:00:42 +0000292 zero then return, otherwise raise :exc:`CalledProcessError`. The
Georg Brandl116aa622007-08-15 14:28:22 +0000293 :exc:`CalledProcessError` object will have the return code in the
294 :attr:`returncode` attribute.
295
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400296 The arguments are the same as for the :func:`call` function. Example::
Georg Brandl116aa622007-08-15 14:28:22 +0000297
Georg Brandl2708f3a2009-12-20 14:38:23 +0000298 >>> subprocess.check_call(["ls", "-l"])
299 0
Georg Brandl116aa622007-08-15 14:28:22 +0000300
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400301 As in the :func:`call` function, if the timeout expires, the child process
302 will be killed and the wait retried. The :exc:`TimeoutExpired` exception
303 will be re-raised after the child process has terminated.
304
Philip Jenveyab7481a2009-05-22 05:46:35 +0000305 .. warning::
306
307 See the warning for :func:`call`.
308
Reid Kleckner28f13032011-03-14 12:36:53 -0400309 .. versionchanged:: 3.3
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400310 *timeout* was added.
Georg Brandl116aa622007-08-15 14:28:22 +0000311
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400312
313.. function:: check_output(*popenargs, timeout=None, **kwargs)
Georg Brandlf9734072008-12-07 15:30:06 +0000314
Gregory P. Smitha454ef62011-05-22 22:29:49 -0700315 Run command with arguments and return its output as a bytes object.
Georg Brandlf9734072008-12-07 15:30:06 +0000316
Benjamin Petersonaa069002009-01-23 03:26:36 +0000317 If the exit code was non-zero it raises a :exc:`CalledProcessError`. The
318 :exc:`CalledProcessError` object will have the return code in the
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400319 :attr:`returncode` attribute and output in the :attr:`output` attribute.
Georg Brandlf9734072008-12-07 15:30:06 +0000320
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400321 The arguments are the same as for the :func:`call` function. Example::
Georg Brandlf9734072008-12-07 15:30:06 +0000322
323 >>> subprocess.check_output(["ls", "-l", "/dev/null"])
Georg Brandl2708f3a2009-12-20 14:38:23 +0000324 b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000325
326 The stdout argument is not allowed as it is used internally.
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000327 To capture standard error in the result, use ``stderr=subprocess.STDOUT``::
Georg Brandlf9734072008-12-07 15:30:06 +0000328
329 >>> subprocess.check_output(
Georg Brandl2708f3a2009-12-20 14:38:23 +0000330 ... ["/bin/sh", "-c", "ls non_existent_file; exit 0"],
331 ... stderr=subprocess.STDOUT)
332 b'ls: non_existent_file: No such file or directory\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000333
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400334 As in the :func:`call` function, if the timeout expires, the child process
335 will be killed and the wait retried. The :exc:`TimeoutExpired` exception
336 will be re-raised after the child process has terminated. The output from
337 the child process so far will be in the :attr:`output` attribute of the
338 exception.
339
Georg Brandlf9734072008-12-07 15:30:06 +0000340 .. versionadded:: 3.1
341
Reid Kleckner28f13032011-03-14 12:36:53 -0400342 .. versionchanged:: 3.3
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400343 *timeout* was added.
344
Georg Brandlf9734072008-12-07 15:30:06 +0000345
Brett Cannona23810f2008-05-26 19:04:21 +0000346.. function:: getstatusoutput(cmd)
Georg Brandl682d7e02010-10-06 10:26:05 +0000347
Brett Cannona23810f2008-05-26 19:04:21 +0000348 Return ``(status, output)`` of executing *cmd* in a shell.
349
350 Execute the string *cmd* in a shell with :func:`os.popen` and return a 2-tuple
351 ``(status, output)``. *cmd* is actually run as ``{ cmd ; } 2>&1``, so that the
352 returned output will contain output or error messages. A trailing newline is
353 stripped from the output. The exit status for the command can be interpreted
Georg Brandl60203b42010-10-06 10:11:56 +0000354 according to the rules for the C function :c:func:`wait`. Example::
Brett Cannona23810f2008-05-26 19:04:21 +0000355
Brett Cannona23810f2008-05-26 19:04:21 +0000356 >>> subprocess.getstatusoutput('ls /bin/ls')
357 (0, '/bin/ls')
358 >>> subprocess.getstatusoutput('cat /bin/junk')
359 (256, 'cat: /bin/junk: No such file or directory')
360 >>> subprocess.getstatusoutput('/bin/junk')
361 (256, 'sh: /bin/junk: not found')
362
Georg Brandl7d418902008-12-27 19:08:11 +0000363 Availability: UNIX.
364
Brett Cannona23810f2008-05-26 19:04:21 +0000365
366.. function:: getoutput(cmd)
Georg Brandl682d7e02010-10-06 10:26:05 +0000367
Georg Brandlf9734072008-12-07 15:30:06 +0000368 Return output (stdout and stderr) of executing *cmd* in a shell.
Brett Cannona23810f2008-05-26 19:04:21 +0000369
370 Like :func:`getstatusoutput`, except the exit status is ignored and the return
371 value is a string containing the command's output. Example::
372
Brett Cannona23810f2008-05-26 19:04:21 +0000373 >>> subprocess.getoutput('ls /bin/ls')
374 '/bin/ls'
375
Georg Brandl7d418902008-12-27 19:08:11 +0000376 Availability: UNIX.
377
Brett Cannona23810f2008-05-26 19:04:21 +0000378
Georg Brandl116aa622007-08-15 14:28:22 +0000379Exceptions
380^^^^^^^^^^
381
382Exceptions raised in the child process, before the new program has started to
383execute, will be re-raised in the parent. Additionally, the exception object
384will have one extra attribute called :attr:`child_traceback`, which is a string
Georg Brandl81675612010-08-26 14:30:56 +0000385containing traceback information from the child's point of view.
Georg Brandl116aa622007-08-15 14:28:22 +0000386
387The most common exception raised is :exc:`OSError`. This occurs, for example,
388when trying to execute a non-existent file. Applications should prepare for
389:exc:`OSError` exceptions.
390
391A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid
392arguments.
393
394check_call() will raise :exc:`CalledProcessError`, if the called process returns
395a non-zero return code.
396
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400397All of the functions and methods that accept a *timeout* parameter, such as
398:func:`call` and :meth:`Popen.communicate` will raise :exc:`TimeoutExpired` if
399the timeout expires before the process exits.
400
Ronald Oussorenc1577902011-03-16 10:03:10 -0400401Exceptions defined in this module all inherit from :exc:`SubprocessError`.
Gregory P. Smith54d412e2011-03-14 14:08:43 -0400402
403 .. versionadded:: 3.3
404 The :exc:`SubprocessError` base class was added.
405
Georg Brandl116aa622007-08-15 14:28:22 +0000406
407Security
408^^^^^^^^
409
410Unlike some other popen functions, this implementation will never call /bin/sh
411implicitly. This means that all characters, including shell metacharacters, can
412safely be passed to child processes.
413
414
415Popen Objects
416-------------
417
418Instances of the :class:`Popen` class have the following methods:
419
420
421.. method:: Popen.poll()
422
Christian Heimes7f044312008-01-06 17:05:40 +0000423 Check if child process has terminated. Set and return :attr:`returncode`
424 attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000425
426
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400427.. method:: Popen.wait(timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000428
Christian Heimes7f044312008-01-06 17:05:40 +0000429 Wait for child process to terminate. Set and return :attr:`returncode`
430 attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000431
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400432 If the process does not terminate after *timeout* seconds, raise a
433 :exc:`TimeoutExpired` exception. It is safe to catch this exception and
434 retry the wait.
435
Georg Brandl734e2682008-08-12 08:18:18 +0000436 .. warning::
437
Philip Jenveyb0896842009-12-03 02:29:36 +0000438 This will deadlock when using ``stdout=PIPE`` and/or
439 ``stderr=PIPE`` and the child process generates enough output to
440 a pipe such that it blocks waiting for the OS pipe buffer to
441 accept more data. Use :meth:`communicate` to avoid that.
Georg Brandl734e2682008-08-12 08:18:18 +0000442
Reid Kleckner28f13032011-03-14 12:36:53 -0400443 .. versionchanged:: 3.3
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400444 *timeout* was added.
Georg Brandl116aa622007-08-15 14:28:22 +0000445
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400446
447.. method:: Popen.communicate(input=None, timeout=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000448
449 Interact with process: Send data to stdin. Read data from stdout and stderr,
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400450 until end-of-file is reached. Wait for process to terminate. The optional
Gregory P. Smitha454ef62011-05-22 22:29:49 -0700451 *input* argument should be data to be sent to the child process, or
452 ``None``, if no data should be sent to the child. The type of *input*
453 must be bytes or, if *universal_newlines* was ``True``, a string.
Georg Brandl116aa622007-08-15 14:28:22 +0000454
Georg Brandlaf265f42008-12-07 15:06:20 +0000455 :meth:`communicate` returns a tuple ``(stdoutdata, stderrdata)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000456
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000457 Note that if you want to send data to the process's stdin, you need to create
458 the Popen object with ``stdin=PIPE``. Similarly, to get anything other than
459 ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or
460 ``stderr=PIPE`` too.
461
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400462 If the process does not terminate after *timeout* seconds, a
463 :exc:`TimeoutExpired` exception will be raised. Catching this exception and
464 retrying communication will not lose any output.
465
466 The child process is not killed if the timeout expires, so in order to
467 cleanup properly a well-behaved application should kill the child process and
468 finish communication::
469
470 proc = subprocess.Popen(...)
471 try:
472 outs, errs = proc.communicate(timeout=15)
473 except TimeoutExpired:
474 proc.kill()
475 outs, errs = proc.communicate()
476
Christian Heimes7f044312008-01-06 17:05:40 +0000477 .. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000478
Christian Heimes7f044312008-01-06 17:05:40 +0000479 The data read is buffered in memory, so do not use this method if the data
480 size is large or unlimited.
481
Reid Kleckner28f13032011-03-14 12:36:53 -0400482 .. versionchanged:: 3.3
Reid Kleckner31aa7dd2011-03-14 12:02:10 -0400483 *timeout* was added.
484
Georg Brandl116aa622007-08-15 14:28:22 +0000485
Christian Heimesa342c012008-04-20 21:01:16 +0000486.. method:: Popen.send_signal(signal)
487
488 Sends the signal *signal* to the child.
489
490 .. note::
491
Brian Curtineb24d742010-04-12 17:16:38 +0000492 On Windows, SIGTERM is an alias for :meth:`terminate`. CTRL_C_EVENT and
Senthil Kumaran916bd382010-10-15 12:55:19 +0000493 CTRL_BREAK_EVENT can be sent to processes started with a *creationflags*
Brian Curtineb24d742010-04-12 17:16:38 +0000494 parameter which includes `CREATE_NEW_PROCESS_GROUP`.
Christian Heimesa342c012008-04-20 21:01:16 +0000495
Christian Heimesa342c012008-04-20 21:01:16 +0000496
497.. method:: Popen.terminate()
498
499 Stop the child. On Posix OSs the method sends SIGTERM to the
Georg Brandl60203b42010-10-06 10:11:56 +0000500 child. On Windows the Win32 API function :c:func:`TerminateProcess` is called
Christian Heimesa342c012008-04-20 21:01:16 +0000501 to stop the child.
502
Christian Heimesa342c012008-04-20 21:01:16 +0000503
504.. method:: Popen.kill()
505
506 Kills the child. On Posix OSs the function sends SIGKILL to the child.
507 On Windows :meth:`kill` is an alias for :meth:`terminate`.
508
Christian Heimesa342c012008-04-20 21:01:16 +0000509
Georg Brandl116aa622007-08-15 14:28:22 +0000510The following attributes are also available:
511
Georg Brandl734e2682008-08-12 08:18:18 +0000512.. warning::
513
Georg Brandle720c0a2009-04-27 16:20:50 +0000514 Use :meth:`communicate` rather than :attr:`.stdin.write <stdin>`,
515 :attr:`.stdout.read <stdout>` or :attr:`.stderr.read <stderr>` to avoid
516 deadlocks due to any of the other OS pipe buffers filling up and blocking the
517 child process.
Georg Brandl734e2682008-08-12 08:18:18 +0000518
519
Georg Brandl116aa622007-08-15 14:28:22 +0000520.. attribute:: Popen.stdin
521
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000522 If the *stdin* argument was :data:`PIPE`, this attribute is a :term:`file
523 object` that provides input to the child process. Otherwise, it is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000524
525
526.. attribute:: Popen.stdout
527
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000528 If the *stdout* argument was :data:`PIPE`, this attribute is a :term:`file
529 object` that provides output from the child process. Otherwise, it is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000530
531
532.. attribute:: Popen.stderr
533
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000534 If the *stderr* argument was :data:`PIPE`, this attribute is a :term:`file
535 object` that provides error output from the child process. Otherwise, it is
Georg Brandlaf265f42008-12-07 15:06:20 +0000536 ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000537
538
539.. attribute:: Popen.pid
540
541 The process ID of the child process.
542
Georg Brandl58bfdca2010-03-21 09:50:49 +0000543 Note that if you set the *shell* argument to ``True``, this is the process ID
544 of the spawned shell.
545
Georg Brandl116aa622007-08-15 14:28:22 +0000546
547.. attribute:: Popen.returncode
548
Christian Heimes7f044312008-01-06 17:05:40 +0000549 The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly
550 by :meth:`communicate`). A ``None`` value indicates that the process
551 hasn't terminated yet.
Georg Brandl48310cd2009-01-03 21:18:54 +0000552
Christian Heimes7f044312008-01-06 17:05:40 +0000553 A negative value ``-N`` indicates that the child was terminated by signal
554 ``N`` (Unix only).
Georg Brandl116aa622007-08-15 14:28:22 +0000555
556
Brian Curtine6242d72011-04-29 22:17:51 -0500557Windows Popen Helpers
558---------------------
559
560The :class:`STARTUPINFO` class and following constants are only available
561on Windows.
562
563.. class:: STARTUPINFO()
Brian Curtin73365dd2011-04-29 22:18:33 -0500564
Brian Curtine6242d72011-04-29 22:17:51 -0500565 Partial support of the Windows
566 `STARTUPINFO <http://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx>`__
567 structure is used for :class:`Popen` creation.
568
569 .. attribute:: dwFlags
570
Senthil Kumarana6bac952011-07-04 11:28:30 -0700571 A bit field that determines whether certain :class:`STARTUPINFO`
572 attributes are used when the process creates a window. ::
Brian Curtine6242d72011-04-29 22:17:51 -0500573
574 si = subprocess.STARTUPINFO()
575 si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
576
577 .. attribute:: hStdInput
578
Senthil Kumarana6bac952011-07-04 11:28:30 -0700579 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
580 is the standard input handle for the process. If
581 :data:`STARTF_USESTDHANDLES` is not specified, the default for standard
582 input is the keyboard buffer.
Brian Curtine6242d72011-04-29 22:17:51 -0500583
584 .. attribute:: hStdOutput
585
Senthil Kumarana6bac952011-07-04 11:28:30 -0700586 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
587 is the standard output handle for the process. Otherwise, this attribute
588 is ignored and the default for standard output is the console window's
Brian Curtine6242d72011-04-29 22:17:51 -0500589 buffer.
590
591 .. attribute:: hStdError
592
Senthil Kumarana6bac952011-07-04 11:28:30 -0700593 If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
594 is the standard error handle for the process. Otherwise, this attribute is
Brian Curtine6242d72011-04-29 22:17:51 -0500595 ignored and the default for standard error is the console window's buffer.
596
597 .. attribute:: wShowWindow
598
Senthil Kumarana6bac952011-07-04 11:28:30 -0700599 If :attr:`dwFlags` specifies :data:`STARTF_USESHOWWINDOW`, this attribute
Brian Curtine6242d72011-04-29 22:17:51 -0500600 can be any of the values that can be specified in the ``nCmdShow``
601 parameter for the
602 `ShowWindow <http://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx>`__
Senthil Kumarana6bac952011-07-04 11:28:30 -0700603 function, except for ``SW_SHOWDEFAULT``. Otherwise, this attribute is
Brian Curtine6242d72011-04-29 22:17:51 -0500604 ignored.
Brian Curtin73365dd2011-04-29 22:18:33 -0500605
Brian Curtine6242d72011-04-29 22:17:51 -0500606 :data:`SW_HIDE` is provided for this attribute. It is used when
607 :class:`Popen` is called with ``shell=True``.
608
609
610Constants
611^^^^^^^^^
612
613The :mod:`subprocess` module exposes the following constants.
614
615.. data:: STD_INPUT_HANDLE
616
617 The standard input device. Initially, this is the console input buffer,
618 ``CONIN$``.
619
620.. data:: STD_OUTPUT_HANDLE
621
622 The standard output device. Initially, this is the active console screen
623 buffer, ``CONOUT$``.
624
625.. data:: STD_ERROR_HANDLE
626
627 The standard error device. Initially, this is the active console screen
628 buffer, ``CONOUT$``.
629
630.. data:: SW_HIDE
631
632 Hides the window. Another window will be activated.
633
634.. data:: STARTF_USESTDHANDLES
635
636 Specifies that the :attr:`STARTUPINFO.hStdInput`,
Senthil Kumarana6bac952011-07-04 11:28:30 -0700637 :attr:`STARTUPINFO.hStdOutput`, and :attr:`STARTUPINFO.hStdError` attributes
Brian Curtine6242d72011-04-29 22:17:51 -0500638 contain additional information.
639
640.. data:: STARTF_USESHOWWINDOW
641
Senthil Kumarana6bac952011-07-04 11:28:30 -0700642 Specifies that the :attr:`STARTUPINFO.wShowWindow` attribute contains
Brian Curtine6242d72011-04-29 22:17:51 -0500643 additional information.
644
645.. data:: CREATE_NEW_CONSOLE
646
647 The new process has a new console, instead of inheriting its parent's
648 console (the default).
Brian Curtin73365dd2011-04-29 22:18:33 -0500649
Brian Curtine6242d72011-04-29 22:17:51 -0500650 This flag is always set when :class:`Popen` is created with ``shell=True``.
651
Brian Curtin30401932011-04-29 22:20:57 -0500652.. data:: CREATE_NEW_PROCESS_GROUP
653
654 A :class:`Popen` ``creationflags`` parameter to specify that a new process
655 group will be created. This flag is necessary for using :func:`os.kill`
656 on the subprocess.
657
658 This flag is ignored if :data:`CREATE_NEW_CONSOLE` is specified.
659
Brian Curtine6242d72011-04-29 22:17:51 -0500660
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000661.. _subprocess-replacements:
662
Georg Brandl116aa622007-08-15 14:28:22 +0000663Replacing Older Functions with the subprocess Module
664----------------------------------------------------
665
666In this section, "a ==> b" means that b can be used as a replacement for a.
667
668.. note::
669
670 All functions in this section fail (more or less) silently if the executed
671 program cannot be found; this module raises an :exc:`OSError` exception.
672
673In the following examples, we assume that the subprocess module is imported with
674"from subprocess import \*".
675
676
677Replacing /bin/sh shell backquote
678^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
679
680::
681
682 output=`mycmd myarg`
683 ==>
684 output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
685
686
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000687Replacing shell pipeline
688^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000689
690::
691
692 output=`dmesg | grep hda`
693 ==>
694 p1 = Popen(["dmesg"], stdout=PIPE)
695 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Gregory P. Smithe09d2f12011-02-05 21:47:25 +0000696 p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
Georg Brandl116aa622007-08-15 14:28:22 +0000697 output = p2.communicate()[0]
698
Gregory P. Smithe09d2f12011-02-05 21:47:25 +0000699The p1.stdout.close() call after starting the p2 is important in order for p1
700to receive a SIGPIPE if p2 exits before p1.
Georg Brandl116aa622007-08-15 14:28:22 +0000701
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000702Replacing :func:`os.system`
703^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000704
705::
706
707 sts = os.system("mycmd" + " myarg")
708 ==>
709 p = Popen("mycmd" + " myarg", shell=True)
Alexandre Vassalottie52e3782009-07-17 09:18:18 +0000710 sts = os.waitpid(p.pid, 0)[1]
Georg Brandl116aa622007-08-15 14:28:22 +0000711
712Notes:
713
714* Calling the program through the shell is usually not required.
715
716* It's easier to look at the :attr:`returncode` attribute than the exit status.
717
718A more realistic example would look like this::
719
720 try:
721 retcode = call("mycmd" + " myarg", shell=True)
722 if retcode < 0:
Collin Winterc79461b2007-09-01 23:34:30 +0000723 print("Child was terminated by signal", -retcode, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000724 else:
Collin Winterc79461b2007-09-01 23:34:30 +0000725 print("Child returned", retcode, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000726 except OSError as e:
Collin Winterc79461b2007-09-01 23:34:30 +0000727 print("Execution failed:", e, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000728
729
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000730Replacing the :func:`os.spawn <os.spawnl>` family
731^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000732
733P_NOWAIT example::
734
735 pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
736 ==>
737 pid = Popen(["/bin/mycmd", "myarg"]).pid
738
739P_WAIT example::
740
741 retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
742 ==>
743 retcode = call(["/bin/mycmd", "myarg"])
744
745Vector example::
746
747 os.spawnvp(os.P_NOWAIT, path, args)
748 ==>
749 Popen([path] + args[1:])
750
751Environment example::
752
753 os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
754 ==>
755 Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
756
757
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000758
759Replacing :func:`os.popen`, :func:`os.popen2`, :func:`os.popen3`
760^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000761
762::
763
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000764 (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
Georg Brandl116aa622007-08-15 14:28:22 +0000765 ==>
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000766 p = Popen(cmd, shell=True, bufsize=bufsize,
767 stdin=PIPE, stdout=PIPE, close_fds=True)
768 (child_stdin, child_stdout) = (p.stdin, p.stdout)
Georg Brandl116aa622007-08-15 14:28:22 +0000769
770::
771
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000772 (child_stdin,
773 child_stdout,
774 child_stderr) = os.popen3(cmd, mode, bufsize)
Georg Brandl116aa622007-08-15 14:28:22 +0000775 ==>
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000776 p = Popen(cmd, shell=True, bufsize=bufsize,
777 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
778 (child_stdin,
779 child_stdout,
780 child_stderr) = (p.stdin, p.stdout, p.stderr)
781
782::
783
784 (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
785 ==>
786 p = Popen(cmd, shell=True, bufsize=bufsize,
787 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
788 (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
789
790Return code handling translates as follows::
791
792 pipe = os.popen(cmd, 'w')
793 ...
794 rc = pipe.close()
Stefan Krahfc9e08d2010-07-14 10:16:11 +0000795 if rc is not None and rc >> 8:
Ezio Melotti985e24d2009-09-13 07:54:02 +0000796 print("There were some errors")
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000797 ==>
798 process = Popen(cmd, 'w', stdin=PIPE)
799 ...
800 process.stdin.close()
801 if process.wait() != 0:
Ezio Melotti985e24d2009-09-13 07:54:02 +0000802 print("There were some errors")
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000803
804
805Replacing functions from the :mod:`popen2` module
806^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
807
808.. note::
809
810 If the cmd argument to popen2 functions is a string, the command is executed
811 through /bin/sh. If it is a list, the command is directly executed.
812
813::
814
815 (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
816 ==>
817 p = Popen(["somestring"], shell=True, bufsize=bufsize,
818 stdin=PIPE, stdout=PIPE, close_fds=True)
819 (child_stdout, child_stdin) = (p.stdout, p.stdin)
820
821::
822
823 (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
824 ==>
825 p = Popen(["mycmd", "myarg"], bufsize=bufsize,
826 stdin=PIPE, stdout=PIPE, close_fds=True)
827 (child_stdout, child_stdin) = (p.stdout, p.stdin)
828
829:class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as
830:class:`subprocess.Popen`, except that:
831
832* :class:`Popen` raises an exception if the execution fails.
833
834* the *capturestderr* argument is replaced with the *stderr* argument.
835
836* ``stdin=PIPE`` and ``stdout=PIPE`` must be specified.
837
838* popen2 closes all file descriptors by default, but you have to specify
Gregory P. Smithf5604852010-12-13 06:45:02 +0000839 ``close_fds=True`` with :class:`Popen` to guarantee this behavior on
840 all platforms or past Python versions.
Eli Bendersky046a7642011-04-15 07:23:26 +0300841
842Notes
843-----
844
845.. _converting-argument-sequence:
846
847Converting an argument sequence to a string on Windows
848^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
849
850On Windows, an *args* sequence is converted to a string that can be parsed
851using the following rules (which correspond to the rules used by the MS C
852runtime):
853
8541. Arguments are delimited by white space, which is either a
855 space or a tab.
856
8572. A string surrounded by double quotation marks is
858 interpreted as a single argument, regardless of white space
859 contained within. A quoted string can be embedded in an
860 argument.
861
8623. A double quotation mark preceded by a backslash is
863 interpreted as a literal double quotation mark.
864
8654. Backslashes are interpreted literally, unless they
866 immediately precede a double quotation mark.
867
8685. If backslashes immediately precede a double quotation mark,
869 every pair of backslashes is interpreted as a literal
870 backslash. If the number of backslashes is odd, the last
871 backslash escapes the next double quotation mark as
872 described in rule 3.
873
Eli Benderskyd2112312011-04-15 07:26:28 +0300874
Éric Araujo9bce3112011-07-27 18:29:31 +0200875.. seealso::
876
877 :mod:`shlex`
878 Module which provides function to parse and escape command lines.