blob: 3318d430ec1ea2837ce4d4ab7a118030f1d71fec [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`subprocess` --- Subprocess management
3===========================================
4
5.. module:: subprocess
6 :synopsis: Subprocess management.
7.. moduleauthor:: Peter Åstrand <astrand@lysator.liu.se>
8.. sectionauthor:: Peter Åstrand <astrand@lysator.liu.se>
9
10
Georg Brandl116aa622007-08-15 14:28:22 +000011The :mod:`subprocess` module allows you to spawn new processes, connect to their
12input/output/error pipes, and obtain their return codes. This module intends to
13replace several other, older modules and functions, such as::
14
15 os.system
16 os.spawn*
Georg Brandl116aa622007-08-15 14:28:22 +000017
18Information about how the :mod:`subprocess` module can be used to replace these
19modules and functions can be found in the following sections.
20
Benjamin Peterson41181742008-07-02 20:22:54 +000021.. seealso::
22
23 :pep:`324` -- PEP proposing the subprocess module
24
Georg Brandl116aa622007-08-15 14:28:22 +000025
26Using the subprocess Module
27---------------------------
28
29This module defines one class called :class:`Popen`:
30
31
32.. class:: Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)
33
34 Arguments are:
35
Benjamin Petersond18de0e2008-07-31 20:21:46 +000036 *args* should be a string, or a sequence of program arguments. The program
Benjamin Petersonfa0d7032009-06-01 22:42:33 +000037 to execute is normally the first item in the args sequence or the string if
38 a string is given, but can be explicitly set by using the *executable*
39 argument. When *executable* is given, the first item in the args sequence
40 is still treated by most programs as the command name, which can then be
41 different from the actual executable name. On Unix, it becomes the display
42 name for the executing program in utilities such as :program:`ps`.
Georg Brandl116aa622007-08-15 14:28:22 +000043
44 On Unix, with *shell=False* (default): In this case, the Popen class uses
45 :meth:`os.execvp` to execute the child program. *args* should normally be a
46 sequence. A string will be treated as a sequence with the string as the only
47 item (the program to execute).
48
49 On Unix, with *shell=True*: If args is a string, it specifies the command string
50 to execute through the shell. If *args* is a sequence, the first item specifies
51 the command string, and any additional items will be treated as additional shell
52 arguments.
53
54 On Windows: the :class:`Popen` class uses CreateProcess() to execute the child
55 program, which operates on strings. If *args* is a sequence, it will be
56 converted to a string using the :meth:`list2cmdline` method. Please note that
57 not all MS Windows applications interpret the command line the same way:
58 :meth:`list2cmdline` is designed for applications using the same rules as the MS
59 C runtime.
60
61 *bufsize*, if given, has the same meaning as the corresponding argument to the
62 built-in open() function: :const:`0` means unbuffered, :const:`1` means line
63 buffered, any other positive value means use a buffer of (approximately) that
64 size. A negative *bufsize* means to use the system default, which usually means
65 fully buffered. The default value for *bufsize* is :const:`0` (unbuffered).
66
67 The *executable* argument specifies the program to execute. It is very seldom
68 needed: Usually, the program to execute is defined by the *args* argument. If
69 ``shell=True``, the *executable* argument specifies which shell to use. On Unix,
70 the default shell is :file:`/bin/sh`. On Windows, the default shell is
71 specified by the :envvar:`COMSPEC` environment variable.
72
73 *stdin*, *stdout* and *stderr* specify the executed programs' standard input,
Georg Brandlaf265f42008-12-07 15:06:20 +000074 standard output and standard error file handles, respectively. Valid values
75 are :data:`PIPE`, an existing file descriptor (a positive integer), an
76 existing file object, and ``None``. :data:`PIPE` indicates that a new pipe
77 to the child should be created. With ``None``, no redirection will occur;
78 the child's file handles will be inherited from the parent. Additionally,
79 *stderr* can be :data:`STDOUT`, which indicates that the stderr data from the
80 applications should be captured into the same file handle as for stdout.
Georg Brandl116aa622007-08-15 14:28:22 +000081
82 If *preexec_fn* is set to a callable object, this object will be called in the
83 child process just before the child is executed. (Unix only)
84
85 If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and
86 :const:`2` will be closed before the child process is executed. (Unix only).
87 Or, on Windows, if *close_fds* is true then no handles will be inherited by the
88 child process. Note that on Windows, you cannot set *close_fds* to true and
89 also redirect the standard handles by setting *stdin*, *stdout* or *stderr*.
90
91 If *shell* is :const:`True`, the specified command will be executed through the
92 shell.
93
94 If *cwd* is not ``None``, the child's current directory will be changed to *cwd*
95 before it is executed. Note that this directory is not considered when
96 searching the executable, so you can't specify the program's path relative to
97 *cwd*.
98
Christian Heimesa342c012008-04-20 21:01:16 +000099 If *env* is not ``None``, it must be a mapping that defines the environment
100 variables for the new process; these are used instead of inheriting the current
101 process' environment, which is the default behavior.
Georg Brandl116aa622007-08-15 14:28:22 +0000102
R. David Murray1055e892009-04-16 18:15:32 +0000103 .. note::
R. David Murrayf4ac1492009-04-15 22:35:15 +0000104
R. David Murray1055e892009-04-16 18:15:32 +0000105 If specified, *env* must provide any variables required
106 for the program to execute. On Windows, in order to run a
107 `side-by-side assembly`_ the specified *env* **must** include a valid
R. David Murrayf4ac1492009-04-15 22:35:15 +0000108 :envvar:`SystemRoot`.
109
R. David Murray1055e892009-04-16 18:15:32 +0000110 .. _side-by-side assembly: http://en.wikipedia.org/wiki/Side-by-Side_Assembly
111
Georg Brandl116aa622007-08-15 14:28:22 +0000112 If *universal_newlines* is :const:`True`, the file objects stdout and stderr are
113 opened as text files, but lines may be terminated by any of ``'\n'``, the Unix
Georg Brandlc575c902008-09-13 17:46:05 +0000114 end-of-line convention, ``'\r'``, the old Macintosh convention or ``'\r\n'``, the
Georg Brandl116aa622007-08-15 14:28:22 +0000115 Windows convention. All of these external representations are seen as ``'\n'``
116 by the Python program.
117
118 .. note::
119
120 This feature is only available if Python is built with universal newline support
121 (the default). Also, the newlines attribute of the file objects :attr:`stdout`,
Georg Brandle11787a2008-07-01 19:10:52 +0000122 :attr:`stdin` and :attr:`stderr` are not updated by the :meth:`communicate` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000123
124 The *startupinfo* and *creationflags*, if given, will be passed to the
125 underlying CreateProcess() function. They can specify things such as appearance
126 of the main window and priority for the new process. (Windows only)
127
128
Georg Brandlaf265f42008-12-07 15:06:20 +0000129.. data:: PIPE
130
131 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
132 to :class:`Popen` and indicates that a pipe to the standard stream should be
133 opened.
134
135
136.. data:: STDOUT
137
138 Special value that can be used as the *stderr* argument to :class:`Popen` and
139 indicates that standard error should go into the same handle as standard
140 output.
Georg Brandl48310cd2009-01-03 21:18:54 +0000141
Georg Brandlaf265f42008-12-07 15:06:20 +0000142
Georg Brandl116aa622007-08-15 14:28:22 +0000143Convenience Functions
144^^^^^^^^^^^^^^^^^^^^^
145
Brett Cannona23810f2008-05-26 19:04:21 +0000146This module also defines four shortcut functions:
Georg Brandl116aa622007-08-15 14:28:22 +0000147
148
149.. function:: call(*popenargs, **kwargs)
150
151 Run command with arguments. Wait for command to complete, then return the
152 :attr:`returncode` attribute.
153
154 The arguments are the same as for the Popen constructor. Example::
155
156 retcode = call(["ls", "-l"])
157
Philip Jenveyab7481a2009-05-22 05:46:35 +0000158 .. warning::
159
160 Like :meth:`Popen.wait`, this will deadlock if the child process
161 generates enough output to a stdout or stderr pipe such that it blocks
162 waiting for the OS pipe buffer to accept more data.
163
Georg Brandl116aa622007-08-15 14:28:22 +0000164
165.. function:: check_call(*popenargs, **kwargs)
166
167 Run command with arguments. Wait for command to complete. If the exit code was
Benjamin Petersone5384b02008-10-04 22:00:42 +0000168 zero then return, otherwise raise :exc:`CalledProcessError`. The
Georg Brandl116aa622007-08-15 14:28:22 +0000169 :exc:`CalledProcessError` object will have the return code in the
170 :attr:`returncode` attribute.
171
172 The arguments are the same as for the Popen constructor. Example::
173
174 check_call(["ls", "-l"])
175
Philip Jenveyab7481a2009-05-22 05:46:35 +0000176 .. warning::
177
178 See the warning for :func:`call`.
179
Georg Brandl116aa622007-08-15 14:28:22 +0000180
Georg Brandlf9734072008-12-07 15:30:06 +0000181.. function:: check_output(*popenargs, **kwargs)
182
183 Run command with arguments and return its output as a byte string.
184
Benjamin Petersonaa069002009-01-23 03:26:36 +0000185 If the exit code was non-zero it raises a :exc:`CalledProcessError`. The
186 :exc:`CalledProcessError` object will have the return code in the
187 :attr:`returncode`
188 attribute and output in the :attr:`output` attribute.
Georg Brandlf9734072008-12-07 15:30:06 +0000189
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000190 The arguments are the same as for the :class:`Popen` constructor. Example::
Georg Brandlf9734072008-12-07 15:30:06 +0000191
192 >>> subprocess.check_output(["ls", "-l", "/dev/null"])
193 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
194
195 The stdout argument is not allowed as it is used internally.
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000196 To capture standard error in the result, use ``stderr=subprocess.STDOUT``::
Georg Brandlf9734072008-12-07 15:30:06 +0000197
198 >>> subprocess.check_output(
Mark Dickinson934896d2009-02-21 20:59:32 +0000199 ["/bin/sh", "-c", "ls non_existent_file ; exit 0"],
Georg Brandlf9734072008-12-07 15:30:06 +0000200 stderr=subprocess.STDOUT)
Mark Dickinson934896d2009-02-21 20:59:32 +0000201 'ls: non_existent_file: No such file or directory\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000202
203 .. versionadded:: 3.1
204
205
Brett Cannona23810f2008-05-26 19:04:21 +0000206.. function:: getstatusoutput(cmd)
207 Return ``(status, output)`` of executing *cmd* in a shell.
208
209 Execute the string *cmd* in a shell with :func:`os.popen` and return a 2-tuple
210 ``(status, output)``. *cmd* is actually run as ``{ cmd ; } 2>&1``, so that the
211 returned output will contain output or error messages. A trailing newline is
212 stripped from the output. The exit status for the command can be interpreted
213 according to the rules for the C function :cfunc:`wait`. Example::
214
215 >>> import subprocess
216 >>> subprocess.getstatusoutput('ls /bin/ls')
217 (0, '/bin/ls')
218 >>> subprocess.getstatusoutput('cat /bin/junk')
219 (256, 'cat: /bin/junk: No such file or directory')
220 >>> subprocess.getstatusoutput('/bin/junk')
221 (256, 'sh: /bin/junk: not found')
222
Georg Brandl7d418902008-12-27 19:08:11 +0000223 Availability: UNIX.
224
Brett Cannona23810f2008-05-26 19:04:21 +0000225
226.. function:: getoutput(cmd)
Georg Brandlf9734072008-12-07 15:30:06 +0000227 Return output (stdout and stderr) of executing *cmd* in a shell.
Brett Cannona23810f2008-05-26 19:04:21 +0000228
229 Like :func:`getstatusoutput`, except the exit status is ignored and the return
230 value is a string containing the command's output. Example::
231
232 >>> import subprocess
233 >>> subprocess.getoutput('ls /bin/ls')
234 '/bin/ls'
235
Georg Brandl7d418902008-12-27 19:08:11 +0000236 Availability: UNIX.
237
Brett Cannona23810f2008-05-26 19:04:21 +0000238
Georg Brandl116aa622007-08-15 14:28:22 +0000239Exceptions
240^^^^^^^^^^
241
242Exceptions raised in the child process, before the new program has started to
243execute, will be re-raised in the parent. Additionally, the exception object
244will have one extra attribute called :attr:`child_traceback`, which is a string
245containing traceback information from the childs point of view.
246
247The most common exception raised is :exc:`OSError`. This occurs, for example,
248when trying to execute a non-existent file. Applications should prepare for
249:exc:`OSError` exceptions.
250
251A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid
252arguments.
253
254check_call() will raise :exc:`CalledProcessError`, if the called process returns
255a non-zero return code.
256
257
258Security
259^^^^^^^^
260
261Unlike some other popen functions, this implementation will never call /bin/sh
262implicitly. This means that all characters, including shell metacharacters, can
263safely be passed to child processes.
264
265
266Popen Objects
267-------------
268
269Instances of the :class:`Popen` class have the following methods:
270
271
272.. method:: Popen.poll()
273
Christian Heimes7f044312008-01-06 17:05:40 +0000274 Check if child process has terminated. Set and return :attr:`returncode`
275 attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000276
277
278.. method:: Popen.wait()
279
Christian Heimes7f044312008-01-06 17:05:40 +0000280 Wait for child process to terminate. Set and return :attr:`returncode`
281 attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000282
Georg Brandl734e2682008-08-12 08:18:18 +0000283 .. warning::
284
285 This will deadlock if the child process generates enough output to a
286 stdout or stderr pipe such that it blocks waiting for the OS pipe buffer
287 to accept more data. Use :meth:`communicate` to avoid that.
288
Georg Brandl116aa622007-08-15 14:28:22 +0000289
290.. method:: Popen.communicate(input=None)
291
292 Interact with process: Send data to stdin. Read data from stdout and stderr,
293 until end-of-file is reached. Wait for process to terminate. The optional
Georg Brandle11787a2008-07-01 19:10:52 +0000294 *input* argument should be a byte string to be sent to the child process, or
Georg Brandl116aa622007-08-15 14:28:22 +0000295 ``None``, if no data should be sent to the child.
296
Georg Brandlaf265f42008-12-07 15:06:20 +0000297 :meth:`communicate` returns a tuple ``(stdoutdata, stderrdata)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000298
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000299 Note that if you want to send data to the process's stdin, you need to create
300 the Popen object with ``stdin=PIPE``. Similarly, to get anything other than
301 ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or
302 ``stderr=PIPE`` too.
303
Christian Heimes7f044312008-01-06 17:05:40 +0000304 .. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000305
Christian Heimes7f044312008-01-06 17:05:40 +0000306 The data read is buffered in memory, so do not use this method if the data
307 size is large or unlimited.
308
Georg Brandl116aa622007-08-15 14:28:22 +0000309
Christian Heimesa342c012008-04-20 21:01:16 +0000310.. method:: Popen.send_signal(signal)
311
312 Sends the signal *signal* to the child.
313
314 .. note::
315
316 On Windows only SIGTERM is supported so far. It's an alias for
317 :meth:`terminate`.
318
Christian Heimesa342c012008-04-20 21:01:16 +0000319
320.. method:: Popen.terminate()
321
322 Stop the child. On Posix OSs the method sends SIGTERM to the
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000323 child. On Windows the Win32 API function :cfunc:`TerminateProcess` is called
Christian Heimesa342c012008-04-20 21:01:16 +0000324 to stop the child.
325
Christian Heimesa342c012008-04-20 21:01:16 +0000326
327.. method:: Popen.kill()
328
329 Kills the child. On Posix OSs the function sends SIGKILL to the child.
330 On Windows :meth:`kill` is an alias for :meth:`terminate`.
331
Christian Heimesa342c012008-04-20 21:01:16 +0000332
Georg Brandl116aa622007-08-15 14:28:22 +0000333The following attributes are also available:
334
Georg Brandl734e2682008-08-12 08:18:18 +0000335.. warning::
336
Georg Brandle720c0a2009-04-27 16:20:50 +0000337 Use :meth:`communicate` rather than :attr:`.stdin.write <stdin>`,
338 :attr:`.stdout.read <stdout>` or :attr:`.stderr.read <stderr>` to avoid
339 deadlocks due to any of the other OS pipe buffers filling up and blocking the
340 child process.
Georg Brandl734e2682008-08-12 08:18:18 +0000341
342
Georg Brandl116aa622007-08-15 14:28:22 +0000343.. attribute:: Popen.stdin
344
Georg Brandlaf265f42008-12-07 15:06:20 +0000345 If the *stdin* argument was :data:`PIPE`, this attribute is a file object
346 that provides input to the child process. Otherwise, it is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000347
348
349.. attribute:: Popen.stdout
350
Georg Brandlaf265f42008-12-07 15:06:20 +0000351 If the *stdout* argument was :data:`PIPE`, this attribute is a file object
352 that provides output from the child process. Otherwise, it is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000353
354
355.. attribute:: Popen.stderr
356
Georg Brandlaf265f42008-12-07 15:06:20 +0000357 If the *stderr* argument was :data:`PIPE`, this attribute is a file object
358 that provides error output from the child process. Otherwise, it is
359 ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000360
361
362.. attribute:: Popen.pid
363
364 The process ID of the child process.
365
366
367.. attribute:: Popen.returncode
368
Christian Heimes7f044312008-01-06 17:05:40 +0000369 The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly
370 by :meth:`communicate`). A ``None`` value indicates that the process
371 hasn't terminated yet.
Georg Brandl48310cd2009-01-03 21:18:54 +0000372
Christian Heimes7f044312008-01-06 17:05:40 +0000373 A negative value ``-N`` indicates that the child was terminated by signal
374 ``N`` (Unix only).
Georg Brandl116aa622007-08-15 14:28:22 +0000375
376
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000377.. _subprocess-replacements:
378
Georg Brandl116aa622007-08-15 14:28:22 +0000379Replacing Older Functions with the subprocess Module
380----------------------------------------------------
381
382In this section, "a ==> b" means that b can be used as a replacement for a.
383
384.. note::
385
386 All functions in this section fail (more or less) silently if the executed
387 program cannot be found; this module raises an :exc:`OSError` exception.
388
389In the following examples, we assume that the subprocess module is imported with
390"from subprocess import \*".
391
392
393Replacing /bin/sh shell backquote
394^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
395
396::
397
398 output=`mycmd myarg`
399 ==>
400 output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
401
402
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000403Replacing shell pipeline
404^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000405
406::
407
408 output=`dmesg | grep hda`
409 ==>
410 p1 = Popen(["dmesg"], stdout=PIPE)
411 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
412 output = p2.communicate()[0]
413
414
415Replacing os.system()
416^^^^^^^^^^^^^^^^^^^^^
417
418::
419
420 sts = os.system("mycmd" + " myarg")
421 ==>
422 p = Popen("mycmd" + " myarg", shell=True)
423 sts = os.waitpid(p.pid, 0)
424
425Notes:
426
427* Calling the program through the shell is usually not required.
428
429* It's easier to look at the :attr:`returncode` attribute than the exit status.
430
431A more realistic example would look like this::
432
433 try:
434 retcode = call("mycmd" + " myarg", shell=True)
435 if retcode < 0:
Collin Winterc79461b2007-09-01 23:34:30 +0000436 print("Child was terminated by signal", -retcode, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000437 else:
Collin Winterc79461b2007-09-01 23:34:30 +0000438 print("Child returned", retcode, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000439 except OSError as e:
Collin Winterc79461b2007-09-01 23:34:30 +0000440 print("Execution failed:", e, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000441
442
Georg Brandlaf265f42008-12-07 15:06:20 +0000443Replacing the os.spawn family
444^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000445
446P_NOWAIT example::
447
448 pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
449 ==>
450 pid = Popen(["/bin/mycmd", "myarg"]).pid
451
452P_WAIT example::
453
454 retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
455 ==>
456 retcode = call(["/bin/mycmd", "myarg"])
457
458Vector example::
459
460 os.spawnvp(os.P_NOWAIT, path, args)
461 ==>
462 Popen([path] + args[1:])
463
464Environment example::
465
466 os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
467 ==>
468 Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
469
470
Georg Brandlaf265f42008-12-07 15:06:20 +0000471Replacing os.popen
472^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000473
474::
475
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000476 pipe = os.popen(cmd, 'r', bufsize)
Georg Brandl116aa622007-08-15 14:28:22 +0000477 ==>
478 pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
479
480::
481
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000482 pipe = os.popen(cmd, 'w', bufsize)
Georg Brandl116aa622007-08-15 14:28:22 +0000483 ==>
484 pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin