blob: f0a632a71cc1265642c97af2c4d1b3f99e29d159 [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
126 are :data:`PIPE`, an existing file descriptor (a positive integer), an
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000127 existing :term:`file object`, and ``None``. :data:`PIPE` indicates that a
128 new pipe to the child should be created. With ``None``, no redirection will
129 occur; the child's file handles will be inherited from the parent. Additionally,
Georg Brandlaf265f42008-12-07 15:06:20 +0000130 *stderr* can be :data:`STDOUT`, which indicates that the stderr data from the
131 applications should be captured into the same file handle as for stdout.
Georg Brandl116aa622007-08-15 14:28:22 +0000132
133 If *preexec_fn* is set to a callable object, this object will be called in the
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000134 child process just before the child is executed.
135 (Unix only)
136
137 .. warning::
138
139 The *preexec_fn* parameter is not safe to use in the presence of threads
140 in your application. The child process could deadlock before exec is
141 called.
142 If you must use it, keep it trivial! Minimize the number of libraries
143 you call into.
144
145 .. note::
146
147 If you need to modify the environment for the child use the *env*
148 parameter rather than doing it in a *preexec_fn*.
149 The *start_new_session* parameter can take the place of a previously
150 common use of *preexec_fn* to call os.setsid() in the child.
Georg Brandl116aa622007-08-15 14:28:22 +0000151
152 If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and
153 :const:`2` will be closed before the child process is executed. (Unix only).
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000154 The default varies by platform: Always true on Unix. On Windows it is
155 true when *stdin*/*stdout*/*stderr* are :const:`None`, false otherwise.
Gregory P. Smithd23047b2010-12-04 09:10:44 +0000156 On Windows, if *close_fds* is true then no handles will be inherited by the
Georg Brandl116aa622007-08-15 14:28:22 +0000157 child process. Note that on Windows, you cannot set *close_fds* to true and
158 also redirect the standard handles by setting *stdin*, *stdout* or *stderr*.
159
Gregory P. Smith8edd99d2010-12-14 13:43:30 +0000160 .. versionchanged:: 3.2
161 The default for *close_fds* was changed from :const:`False` to
162 what is described above.
163
164 *pass_fds* is an optional sequence of file descriptors to keep open
165 between the parent and child. Providing any *pass_fds* forces
166 *close_fds* to be :const:`True`. (Unix only)
167
168 .. versionadded:: 3.2
169 The *pass_fds* parameter was added.
Georg Brandl116aa622007-08-15 14:28:22 +0000170
171 If *cwd* is not ``None``, the child's current directory will be changed to *cwd*
172 before it is executed. Note that this directory is not considered when
173 searching the executable, so you can't specify the program's path relative to
174 *cwd*.
175
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000176 If *restore_signals* is True (the default) all signals that Python has set to
177 SIG_IGN are restored to SIG_DFL in the child process before the exec.
178 Currently this includes the SIGPIPE, SIGXFZ and SIGXFSZ signals.
179 (Unix only)
180
181 .. versionchanged:: 3.2
182 *restore_signals* was added.
183
184 If *start_new_session* is True the setsid() system call will be made in the
185 child process prior to the execution of the subprocess. (Unix only)
186
187 .. versionchanged:: 3.2
188 *start_new_session* was added.
189
Christian Heimesa342c012008-04-20 21:01:16 +0000190 If *env* is not ``None``, it must be a mapping that defines the environment
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000191 variables for the new process; these are used instead of the default
192 behavior of inheriting the current process' environment.
Georg Brandl116aa622007-08-15 14:28:22 +0000193
R. David Murray1055e892009-04-16 18:15:32 +0000194 .. note::
R. David Murrayf4ac1492009-04-15 22:35:15 +0000195
Georg Brandl2708f3a2009-12-20 14:38:23 +0000196 If specified, *env* must provide any variables required for the program to
197 execute. On Windows, in order to run a `side-by-side assembly`_ the
198 specified *env* **must** include a valid :envvar:`SystemRoot`.
R. David Murrayf4ac1492009-04-15 22:35:15 +0000199
R. David Murray1055e892009-04-16 18:15:32 +0000200 .. _side-by-side assembly: http://en.wikipedia.org/wiki/Side-by-Side_Assembly
201
Georg Brandl116aa622007-08-15 14:28:22 +0000202 If *universal_newlines* is :const:`True`, the file objects stdout and stderr are
203 opened as text files, but lines may be terminated by any of ``'\n'``, the Unix
Georg Brandlc575c902008-09-13 17:46:05 +0000204 end-of-line convention, ``'\r'``, the old Macintosh convention or ``'\r\n'``, the
Georg Brandl116aa622007-08-15 14:28:22 +0000205 Windows convention. All of these external representations are seen as ``'\n'``
206 by the Python program.
207
208 .. note::
209
Georg Brandl7f01a132009-09-16 15:58:14 +0000210 This feature is only available if Python is built with universal newline
211 support (the default). Also, the newlines attribute of the file objects
212 :attr:`stdout`, :attr:`stdin` and :attr:`stderr` are not updated by the
213 :meth:`communicate` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000214
215 The *startupinfo* and *creationflags*, if given, will be passed to the
216 underlying CreateProcess() function. They can specify things such as appearance
217 of the main window and priority for the new process. (Windows only)
218
Brian Curtin79cdb662010-12-03 02:46:02 +0000219 Popen objects are supported as context managers via the :keyword:`with` statement,
220 closing any open file descriptors on exit.
221 ::
222
223 with Popen(["ifconfig"], stdout=PIPE) as proc:
224 log.write(proc.stdout.read())
225
226 .. versionchanged:: 3.2
227 Added context manager support.
228
Georg Brandl116aa622007-08-15 14:28:22 +0000229
Georg Brandlaf265f42008-12-07 15:06:20 +0000230.. data:: PIPE
231
232 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
233 to :class:`Popen` and indicates that a pipe to the standard stream should be
234 opened.
235
236
237.. data:: STDOUT
238
239 Special value that can be used as the *stderr* argument to :class:`Popen` and
240 indicates that standard error should go into the same handle as standard
241 output.
Georg Brandl48310cd2009-01-03 21:18:54 +0000242
Georg Brandlaf265f42008-12-07 15:06:20 +0000243
Georg Brandl116aa622007-08-15 14:28:22 +0000244Convenience Functions
245^^^^^^^^^^^^^^^^^^^^^
246
Brett Cannona23810f2008-05-26 19:04:21 +0000247This module also defines four shortcut functions:
Georg Brandl116aa622007-08-15 14:28:22 +0000248
249
250.. function:: call(*popenargs, **kwargs)
251
252 Run command with arguments. Wait for command to complete, then return the
253 :attr:`returncode` attribute.
254
Benjamin Peterson21896a32010-03-21 22:03:03 +0000255 The arguments are the same as for the :class:`Popen` constructor. Example::
Georg Brandl116aa622007-08-15 14:28:22 +0000256
Georg Brandl2708f3a2009-12-20 14:38:23 +0000257 >>> retcode = subprocess.call(["ls", "-l"])
Georg Brandl116aa622007-08-15 14:28:22 +0000258
Philip Jenveyab7481a2009-05-22 05:46:35 +0000259 .. warning::
260
Philip Jenveyb0896842009-12-03 02:29:36 +0000261 Like :meth:`Popen.wait`, this will deadlock when using
262 ``stdout=PIPE`` and/or ``stderr=PIPE`` and the child process
263 generates enough output to a pipe such that it blocks waiting
264 for the OS pipe buffer to accept more data.
Philip Jenveyab7481a2009-05-22 05:46:35 +0000265
Georg Brandl116aa622007-08-15 14:28:22 +0000266
267.. function:: check_call(*popenargs, **kwargs)
268
269 Run command with arguments. Wait for command to complete. If the exit code was
Benjamin Petersone5384b02008-10-04 22:00:42 +0000270 zero then return, otherwise raise :exc:`CalledProcessError`. The
Georg Brandl116aa622007-08-15 14:28:22 +0000271 :exc:`CalledProcessError` object will have the return code in the
272 :attr:`returncode` attribute.
273
Benjamin Peterson21896a32010-03-21 22:03:03 +0000274 The arguments are the same as for the :class:`Popen` constructor. Example::
Georg Brandl116aa622007-08-15 14:28:22 +0000275
Georg Brandl2708f3a2009-12-20 14:38:23 +0000276 >>> subprocess.check_call(["ls", "-l"])
277 0
Georg Brandl116aa622007-08-15 14:28:22 +0000278
Philip Jenveyab7481a2009-05-22 05:46:35 +0000279 .. warning::
280
281 See the warning for :func:`call`.
282
Georg Brandl116aa622007-08-15 14:28:22 +0000283
Georg Brandlf9734072008-12-07 15:30:06 +0000284.. function:: check_output(*popenargs, **kwargs)
285
286 Run command with arguments and return its output as a byte string.
287
Benjamin Petersonaa069002009-01-23 03:26:36 +0000288 If the exit code was non-zero it raises a :exc:`CalledProcessError`. The
289 :exc:`CalledProcessError` object will have the return code in the
290 :attr:`returncode`
291 attribute and output in the :attr:`output` attribute.
Georg Brandlf9734072008-12-07 15:30:06 +0000292
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000293 The arguments are the same as for the :class:`Popen` constructor. Example::
Georg Brandlf9734072008-12-07 15:30:06 +0000294
295 >>> subprocess.check_output(["ls", "-l", "/dev/null"])
Georg Brandl2708f3a2009-12-20 14:38:23 +0000296 b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000297
298 The stdout argument is not allowed as it is used internally.
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000299 To capture standard error in the result, use ``stderr=subprocess.STDOUT``::
Georg Brandlf9734072008-12-07 15:30:06 +0000300
301 >>> subprocess.check_output(
Georg Brandl2708f3a2009-12-20 14:38:23 +0000302 ... ["/bin/sh", "-c", "ls non_existent_file; exit 0"],
303 ... stderr=subprocess.STDOUT)
304 b'ls: non_existent_file: No such file or directory\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000305
306 .. versionadded:: 3.1
307
308
Brett Cannona23810f2008-05-26 19:04:21 +0000309.. function:: getstatusoutput(cmd)
Georg Brandl682d7e02010-10-06 10:26:05 +0000310
Brett Cannona23810f2008-05-26 19:04:21 +0000311 Return ``(status, output)`` of executing *cmd* in a shell.
312
313 Execute the string *cmd* in a shell with :func:`os.popen` and return a 2-tuple
314 ``(status, output)``. *cmd* is actually run as ``{ cmd ; } 2>&1``, so that the
315 returned output will contain output or error messages. A trailing newline is
316 stripped from the output. The exit status for the command can be interpreted
Georg Brandl60203b42010-10-06 10:11:56 +0000317 according to the rules for the C function :c:func:`wait`. Example::
Brett Cannona23810f2008-05-26 19:04:21 +0000318
Brett Cannona23810f2008-05-26 19:04:21 +0000319 >>> subprocess.getstatusoutput('ls /bin/ls')
320 (0, '/bin/ls')
321 >>> subprocess.getstatusoutput('cat /bin/junk')
322 (256, 'cat: /bin/junk: No such file or directory')
323 >>> subprocess.getstatusoutput('/bin/junk')
324 (256, 'sh: /bin/junk: not found')
325
Georg Brandl7d418902008-12-27 19:08:11 +0000326 Availability: UNIX.
327
Brett Cannona23810f2008-05-26 19:04:21 +0000328
329.. function:: getoutput(cmd)
Georg Brandl682d7e02010-10-06 10:26:05 +0000330
Georg Brandlf9734072008-12-07 15:30:06 +0000331 Return output (stdout and stderr) of executing *cmd* in a shell.
Brett Cannona23810f2008-05-26 19:04:21 +0000332
333 Like :func:`getstatusoutput`, except the exit status is ignored and the return
334 value is a string containing the command's output. Example::
335
Brett Cannona23810f2008-05-26 19:04:21 +0000336 >>> subprocess.getoutput('ls /bin/ls')
337 '/bin/ls'
338
Georg Brandl7d418902008-12-27 19:08:11 +0000339 Availability: UNIX.
340
Brett Cannona23810f2008-05-26 19:04:21 +0000341
Georg Brandl116aa622007-08-15 14:28:22 +0000342Exceptions
343^^^^^^^^^^
344
345Exceptions raised in the child process, before the new program has started to
346execute, will be re-raised in the parent. Additionally, the exception object
347will have one extra attribute called :attr:`child_traceback`, which is a string
Georg Brandl81675612010-08-26 14:30:56 +0000348containing traceback information from the child's point of view.
Georg Brandl116aa622007-08-15 14:28:22 +0000349
350The most common exception raised is :exc:`OSError`. This occurs, for example,
351when trying to execute a non-existent file. Applications should prepare for
352:exc:`OSError` exceptions.
353
354A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid
355arguments.
356
357check_call() will raise :exc:`CalledProcessError`, if the called process returns
358a non-zero return code.
359
360
361Security
362^^^^^^^^
363
364Unlike some other popen functions, this implementation will never call /bin/sh
365implicitly. This means that all characters, including shell metacharacters, can
366safely be passed to child processes.
367
368
369Popen Objects
370-------------
371
372Instances of the :class:`Popen` class have the following methods:
373
374
375.. method:: Popen.poll()
376
Christian Heimes7f044312008-01-06 17:05:40 +0000377 Check if child process has terminated. Set and return :attr:`returncode`
378 attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000379
380
381.. method:: Popen.wait()
382
Christian Heimes7f044312008-01-06 17:05:40 +0000383 Wait for child process to terminate. Set and return :attr:`returncode`
384 attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000385
Georg Brandl734e2682008-08-12 08:18:18 +0000386 .. warning::
387
Philip Jenveyb0896842009-12-03 02:29:36 +0000388 This will deadlock when using ``stdout=PIPE`` and/or
389 ``stderr=PIPE`` and the child process generates enough output to
390 a pipe such that it blocks waiting for the OS pipe buffer to
391 accept more data. Use :meth:`communicate` to avoid that.
Georg Brandl734e2682008-08-12 08:18:18 +0000392
Georg Brandl116aa622007-08-15 14:28:22 +0000393
394.. method:: Popen.communicate(input=None)
395
396 Interact with process: Send data to stdin. Read data from stdout and stderr,
397 until end-of-file is reached. Wait for process to terminate. The optional
Georg Brandle11787a2008-07-01 19:10:52 +0000398 *input* argument should be a byte string to be sent to the child process, or
Georg Brandl116aa622007-08-15 14:28:22 +0000399 ``None``, if no data should be sent to the child.
400
Georg Brandlaf265f42008-12-07 15:06:20 +0000401 :meth:`communicate` returns a tuple ``(stdoutdata, stderrdata)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000402
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000403 Note that if you want to send data to the process's stdin, you need to create
404 the Popen object with ``stdin=PIPE``. Similarly, to get anything other than
405 ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or
406 ``stderr=PIPE`` too.
407
Christian Heimes7f044312008-01-06 17:05:40 +0000408 .. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000409
Christian Heimes7f044312008-01-06 17:05:40 +0000410 The data read is buffered in memory, so do not use this method if the data
411 size is large or unlimited.
412
Georg Brandl116aa622007-08-15 14:28:22 +0000413
Christian Heimesa342c012008-04-20 21:01:16 +0000414.. method:: Popen.send_signal(signal)
415
416 Sends the signal *signal* to the child.
417
418 .. note::
419
Brian Curtineb24d742010-04-12 17:16:38 +0000420 On Windows, SIGTERM is an alias for :meth:`terminate`. CTRL_C_EVENT and
Senthil Kumaran916bd382010-10-15 12:55:19 +0000421 CTRL_BREAK_EVENT can be sent to processes started with a *creationflags*
Brian Curtineb24d742010-04-12 17:16:38 +0000422 parameter which includes `CREATE_NEW_PROCESS_GROUP`.
Christian Heimesa342c012008-04-20 21:01:16 +0000423
Christian Heimesa342c012008-04-20 21:01:16 +0000424
425.. method:: Popen.terminate()
426
427 Stop the child. On Posix OSs the method sends SIGTERM to the
Georg Brandl60203b42010-10-06 10:11:56 +0000428 child. On Windows the Win32 API function :c:func:`TerminateProcess` is called
Christian Heimesa342c012008-04-20 21:01:16 +0000429 to stop the child.
430
Christian Heimesa342c012008-04-20 21:01:16 +0000431
432.. method:: Popen.kill()
433
434 Kills the child. On Posix OSs the function sends SIGKILL to the child.
435 On Windows :meth:`kill` is an alias for :meth:`terminate`.
436
Christian Heimesa342c012008-04-20 21:01:16 +0000437
Georg Brandl116aa622007-08-15 14:28:22 +0000438The following attributes are also available:
439
Georg Brandl734e2682008-08-12 08:18:18 +0000440.. warning::
441
Georg Brandle720c0a2009-04-27 16:20:50 +0000442 Use :meth:`communicate` rather than :attr:`.stdin.write <stdin>`,
443 :attr:`.stdout.read <stdout>` or :attr:`.stderr.read <stderr>` to avoid
444 deadlocks due to any of the other OS pipe buffers filling up and blocking the
445 child process.
Georg Brandl734e2682008-08-12 08:18:18 +0000446
447
Georg Brandl116aa622007-08-15 14:28:22 +0000448.. attribute:: Popen.stdin
449
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000450 If the *stdin* argument was :data:`PIPE`, this attribute is a :term:`file
451 object` that provides input to the child process. Otherwise, it is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000452
453
454.. attribute:: Popen.stdout
455
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000456 If the *stdout* argument was :data:`PIPE`, this attribute is a :term:`file
457 object` that provides output from the child process. Otherwise, it is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000458
459
460.. attribute:: Popen.stderr
461
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000462 If the *stderr* argument was :data:`PIPE`, this attribute is a :term:`file
463 object` that provides error output from the child process. Otherwise, it is
Georg Brandlaf265f42008-12-07 15:06:20 +0000464 ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000465
466
467.. attribute:: Popen.pid
468
469 The process ID of the child process.
470
Georg Brandl58bfdca2010-03-21 09:50:49 +0000471 Note that if you set the *shell* argument to ``True``, this is the process ID
472 of the spawned shell.
473
Georg Brandl116aa622007-08-15 14:28:22 +0000474
475.. attribute:: Popen.returncode
476
Christian Heimes7f044312008-01-06 17:05:40 +0000477 The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly
478 by :meth:`communicate`). A ``None`` value indicates that the process
479 hasn't terminated yet.
Georg Brandl48310cd2009-01-03 21:18:54 +0000480
Christian Heimes7f044312008-01-06 17:05:40 +0000481 A negative value ``-N`` indicates that the child was terminated by signal
482 ``N`` (Unix only).
Georg Brandl116aa622007-08-15 14:28:22 +0000483
484
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000485.. _subprocess-replacements:
486
Georg Brandl116aa622007-08-15 14:28:22 +0000487Replacing Older Functions with the subprocess Module
488----------------------------------------------------
489
490In this section, "a ==> b" means that b can be used as a replacement for a.
491
492.. note::
493
494 All functions in this section fail (more or less) silently if the executed
495 program cannot be found; this module raises an :exc:`OSError` exception.
496
497In the following examples, we assume that the subprocess module is imported with
498"from subprocess import \*".
499
500
501Replacing /bin/sh shell backquote
502^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
503
504::
505
506 output=`mycmd myarg`
507 ==>
508 output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
509
510
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000511Replacing shell pipeline
512^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000513
514::
515
516 output=`dmesg | grep hda`
517 ==>
518 p1 = Popen(["dmesg"], stdout=PIPE)
519 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Gregory P. Smithe09d2f12011-02-05 21:47:25 +0000520 p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
Georg Brandl116aa622007-08-15 14:28:22 +0000521 output = p2.communicate()[0]
522
Gregory P. Smithe09d2f12011-02-05 21:47:25 +0000523The p1.stdout.close() call after starting the p2 is important in order for p1
524to receive a SIGPIPE if p2 exits before p1.
Georg Brandl116aa622007-08-15 14:28:22 +0000525
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000526Replacing :func:`os.system`
527^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000528
529::
530
531 sts = os.system("mycmd" + " myarg")
532 ==>
533 p = Popen("mycmd" + " myarg", shell=True)
Alexandre Vassalottie52e3782009-07-17 09:18:18 +0000534 sts = os.waitpid(p.pid, 0)[1]
Georg Brandl116aa622007-08-15 14:28:22 +0000535
536Notes:
537
538* Calling the program through the shell is usually not required.
539
540* It's easier to look at the :attr:`returncode` attribute than the exit status.
541
542A more realistic example would look like this::
543
544 try:
545 retcode = call("mycmd" + " myarg", shell=True)
546 if retcode < 0:
Collin Winterc79461b2007-09-01 23:34:30 +0000547 print("Child was terminated by signal", -retcode, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000548 else:
Collin Winterc79461b2007-09-01 23:34:30 +0000549 print("Child returned", retcode, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000550 except OSError as e:
Collin Winterc79461b2007-09-01 23:34:30 +0000551 print("Execution failed:", e, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000552
553
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000554Replacing the :func:`os.spawn <os.spawnl>` family
555^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000556
557P_NOWAIT example::
558
559 pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
560 ==>
561 pid = Popen(["/bin/mycmd", "myarg"]).pid
562
563P_WAIT example::
564
565 retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
566 ==>
567 retcode = call(["/bin/mycmd", "myarg"])
568
569Vector example::
570
571 os.spawnvp(os.P_NOWAIT, path, args)
572 ==>
573 Popen([path] + args[1:])
574
575Environment example::
576
577 os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
578 ==>
579 Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
580
581
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000582
583Replacing :func:`os.popen`, :func:`os.popen2`, :func:`os.popen3`
584^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000585
586::
587
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000588 (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
Georg Brandl116aa622007-08-15 14:28:22 +0000589 ==>
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000590 p = Popen(cmd, shell=True, bufsize=bufsize,
591 stdin=PIPE, stdout=PIPE, close_fds=True)
592 (child_stdin, child_stdout) = (p.stdin, p.stdout)
Georg Brandl116aa622007-08-15 14:28:22 +0000593
594::
595
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000596 (child_stdin,
597 child_stdout,
598 child_stderr) = os.popen3(cmd, mode, bufsize)
Georg Brandl116aa622007-08-15 14:28:22 +0000599 ==>
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000600 p = Popen(cmd, shell=True, bufsize=bufsize,
601 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
602 (child_stdin,
603 child_stdout,
604 child_stderr) = (p.stdin, p.stdout, p.stderr)
605
606::
607
608 (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
609 ==>
610 p = Popen(cmd, shell=True, bufsize=bufsize,
611 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
612 (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
613
614Return code handling translates as follows::
615
616 pipe = os.popen(cmd, 'w')
617 ...
618 rc = pipe.close()
Stefan Krahfc9e08d2010-07-14 10:16:11 +0000619 if rc is not None and rc >> 8:
Ezio Melotti985e24d2009-09-13 07:54:02 +0000620 print("There were some errors")
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000621 ==>
622 process = Popen(cmd, 'w', stdin=PIPE)
623 ...
624 process.stdin.close()
625 if process.wait() != 0:
Ezio Melotti985e24d2009-09-13 07:54:02 +0000626 print("There were some errors")
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000627
628
629Replacing functions from the :mod:`popen2` module
630^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
631
632.. note::
633
634 If the cmd argument to popen2 functions is a string, the command is executed
635 through /bin/sh. If it is a list, the command is directly executed.
636
637::
638
639 (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
640 ==>
641 p = Popen(["somestring"], shell=True, bufsize=bufsize,
642 stdin=PIPE, stdout=PIPE, close_fds=True)
643 (child_stdout, child_stdin) = (p.stdout, p.stdin)
644
645::
646
647 (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
648 ==>
649 p = Popen(["mycmd", "myarg"], bufsize=bufsize,
650 stdin=PIPE, stdout=PIPE, close_fds=True)
651 (child_stdout, child_stdin) = (p.stdout, p.stdin)
652
653:class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as
654:class:`subprocess.Popen`, except that:
655
656* :class:`Popen` raises an exception if the execution fails.
657
658* the *capturestderr* argument is replaced with the *stderr* argument.
659
660* ``stdin=PIPE`` and ``stdout=PIPE`` must be specified.
661
662* popen2 closes all file descriptors by default, but you have to specify
Gregory P. Smithf5604852010-12-13 06:45:02 +0000663 ``close_fds=True`` with :class:`Popen` to guarantee this behavior on
664 all platforms or past Python versions.
Eli Bendersky046a7642011-04-15 07:23:26 +0300665
666Notes
667-----
668
669.. _converting-argument-sequence:
670
671Converting an argument sequence to a string on Windows
672^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
673
674On Windows, an *args* sequence is converted to a string that can be parsed
675using the following rules (which correspond to the rules used by the MS C
676runtime):
677
6781. Arguments are delimited by white space, which is either a
679 space or a tab.
680
6812. A string surrounded by double quotation marks is
682 interpreted as a single argument, regardless of white space
683 contained within. A quoted string can be embedded in an
684 argument.
685
6863. A double quotation mark preceded by a backslash is
687 interpreted as a literal double quotation mark.
688
6894. Backslashes are interpreted literally, unless they
690 immediately precede a double quotation mark.
691
6925. If backslashes immediately precede a double quotation mark,
693 every pair of backslashes is interpreted as a literal
694 backslash. If the number of backslashes is odd, the last
695 backslash escapes the next double quotation mark as
696 described in rule 3.
697
Eli Benderskyd2112312011-04-15 07:26:28 +0300698