blob: daa88b368d4ab1756c6899d87a857ba71581aaaa [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
36 *args* should be a string, or a sequence of program arguments. The program to
37 execute is normally the first item in the args sequence or string, but can be
38 explicitly set by using the executable argument.
39
40 On Unix, with *shell=False* (default): In this case, the Popen class uses
41 :meth:`os.execvp` to execute the child program. *args* should normally be a
42 sequence. A string will be treated as a sequence with the string as the only
43 item (the program to execute).
44
45 On Unix, with *shell=True*: If args is a string, it specifies the command string
46 to execute through the shell. If *args* is a sequence, the first item specifies
47 the command string, and any additional items will be treated as additional shell
48 arguments.
49
50 On Windows: the :class:`Popen` class uses CreateProcess() to execute the child
51 program, which operates on strings. If *args* is a sequence, it will be
52 converted to a string using the :meth:`list2cmdline` method. Please note that
53 not all MS Windows applications interpret the command line the same way:
54 :meth:`list2cmdline` is designed for applications using the same rules as the MS
55 C runtime.
56
57 *bufsize*, if given, has the same meaning as the corresponding argument to the
58 built-in open() function: :const:`0` means unbuffered, :const:`1` means line
59 buffered, any other positive value means use a buffer of (approximately) that
60 size. A negative *bufsize* means to use the system default, which usually means
61 fully buffered. The default value for *bufsize* is :const:`0` (unbuffered).
62
63 The *executable* argument specifies the program to execute. It is very seldom
64 needed: Usually, the program to execute is defined by the *args* argument. If
65 ``shell=True``, the *executable* argument specifies which shell to use. On Unix,
66 the default shell is :file:`/bin/sh`. On Windows, the default shell is
67 specified by the :envvar:`COMSPEC` environment variable.
68
69 *stdin*, *stdout* and *stderr* specify the executed programs' standard input,
70 standard output and standard error file handles, respectively. Valid values are
71 ``PIPE``, an existing file descriptor (a positive integer), an existing file
72 object, and ``None``. ``PIPE`` indicates that a new pipe to the child should be
73 created. With ``None``, no redirection will occur; the child's file handles
74 will be inherited from the parent. Additionally, *stderr* can be ``STDOUT``,
75 which indicates that the stderr data from the applications should be captured
76 into the same file handle as for stdout.
77
78 If *preexec_fn* is set to a callable object, this object will be called in the
79 child process just before the child is executed. (Unix only)
80
81 If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and
82 :const:`2` will be closed before the child process is executed. (Unix only).
83 Or, on Windows, if *close_fds* is true then no handles will be inherited by the
84 child process. Note that on Windows, you cannot set *close_fds* to true and
85 also redirect the standard handles by setting *stdin*, *stdout* or *stderr*.
86
87 If *shell* is :const:`True`, the specified command will be executed through the
88 shell.
89
90 If *cwd* is not ``None``, the child's current directory will be changed to *cwd*
91 before it is executed. Note that this directory is not considered when
92 searching the executable, so you can't specify the program's path relative to
93 *cwd*.
94
Christian Heimesa342c012008-04-20 21:01:16 +000095 If *env* is not ``None``, it must be a mapping that defines the environment
96 variables for the new process; these are used instead of inheriting the current
97 process' environment, which is the default behavior.
Georg Brandl116aa622007-08-15 14:28:22 +000098
99 If *universal_newlines* is :const:`True`, the file objects stdout and stderr are
100 opened as text files, but lines may be terminated by any of ``'\n'``, the Unix
101 end-of-line convention, ``'\r'``, the Macintosh convention or ``'\r\n'``, the
102 Windows convention. All of these external representations are seen as ``'\n'``
103 by the Python program.
104
105 .. note::
106
107 This feature is only available if Python is built with universal newline support
108 (the default). Also, the newlines attribute of the file objects :attr:`stdout`,
Georg Brandle11787a2008-07-01 19:10:52 +0000109 :attr:`stdin` and :attr:`stderr` are not updated by the :meth:`communicate` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000110
111 The *startupinfo* and *creationflags*, if given, will be passed to the
112 underlying CreateProcess() function. They can specify things such as appearance
113 of the main window and priority for the new process. (Windows only)
114
115
116Convenience Functions
117^^^^^^^^^^^^^^^^^^^^^
118
Brett Cannona23810f2008-05-26 19:04:21 +0000119This module also defines four shortcut functions:
Georg Brandl116aa622007-08-15 14:28:22 +0000120
121
122.. function:: call(*popenargs, **kwargs)
123
124 Run command with arguments. Wait for command to complete, then return the
125 :attr:`returncode` attribute.
126
127 The arguments are the same as for the Popen constructor. Example::
128
129 retcode = call(["ls", "-l"])
130
131
132.. function:: check_call(*popenargs, **kwargs)
133
134 Run command with arguments. Wait for command to complete. If the exit code was
135 zero then return, otherwise raise :exc:`CalledProcessError.` The
136 :exc:`CalledProcessError` object will have the return code in the
137 :attr:`returncode` attribute.
138
139 The arguments are the same as for the Popen constructor. Example::
140
141 check_call(["ls", "-l"])
142
Georg Brandl116aa622007-08-15 14:28:22 +0000143
Brett Cannona23810f2008-05-26 19:04:21 +0000144.. function:: getstatusoutput(cmd)
145 Return ``(status, output)`` of executing *cmd* in a shell.
146
147 Execute the string *cmd* in a shell with :func:`os.popen` and return a 2-tuple
148 ``(status, output)``. *cmd* is actually run as ``{ cmd ; } 2>&1``, so that the
149 returned output will contain output or error messages. A trailing newline is
150 stripped from the output. The exit status for the command can be interpreted
151 according to the rules for the C function :cfunc:`wait`. Example::
152
153 >>> import subprocess
154 >>> subprocess.getstatusoutput('ls /bin/ls')
155 (0, '/bin/ls')
156 >>> subprocess.getstatusoutput('cat /bin/junk')
157 (256, 'cat: /bin/junk: No such file or directory')
158 >>> subprocess.getstatusoutput('/bin/junk')
159 (256, 'sh: /bin/junk: not found')
160
161
162.. function:: getoutput(cmd)
163 Return output ``(stdout or stderr)`` of executing *cmd* in a shell.
164
165 Like :func:`getstatusoutput`, except the exit status is ignored and the return
166 value is a string containing the command's output. Example::
167
168 >>> import subprocess
169 >>> subprocess.getoutput('ls /bin/ls')
170 '/bin/ls'
171
172
Georg Brandl116aa622007-08-15 14:28:22 +0000173Exceptions
174^^^^^^^^^^
175
176Exceptions raised in the child process, before the new program has started to
177execute, will be re-raised in the parent. Additionally, the exception object
178will have one extra attribute called :attr:`child_traceback`, which is a string
179containing traceback information from the childs point of view.
180
181The most common exception raised is :exc:`OSError`. This occurs, for example,
182when trying to execute a non-existent file. Applications should prepare for
183:exc:`OSError` exceptions.
184
185A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid
186arguments.
187
188check_call() will raise :exc:`CalledProcessError`, if the called process returns
189a non-zero return code.
190
191
192Security
193^^^^^^^^
194
195Unlike some other popen functions, this implementation will never call /bin/sh
196implicitly. This means that all characters, including shell metacharacters, can
197safely be passed to child processes.
198
199
200Popen Objects
201-------------
202
203Instances of the :class:`Popen` class have the following methods:
204
205
206.. method:: Popen.poll()
207
Christian Heimes7f044312008-01-06 17:05:40 +0000208 Check if child process has terminated. Set and return :attr:`returncode`
209 attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000210
211
212.. method:: Popen.wait()
213
Christian Heimes7f044312008-01-06 17:05:40 +0000214 Wait for child process to terminate. Set and return :attr:`returncode`
215 attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000216
217
218.. method:: Popen.communicate(input=None)
219
220 Interact with process: Send data to stdin. Read data from stdout and stderr,
221 until end-of-file is reached. Wait for process to terminate. The optional
Georg Brandle11787a2008-07-01 19:10:52 +0000222 *input* argument should be a byte string to be sent to the child process, or
Georg Brandl116aa622007-08-15 14:28:22 +0000223 ``None``, if no data should be sent to the child.
224
Christian Heimes7f044312008-01-06 17:05:40 +0000225 :meth:`communicate` returns a tuple ``(stdout, stderr)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000226
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000227 Note that if you want to send data to the process's stdin, you need to create
228 the Popen object with ``stdin=PIPE``. Similarly, to get anything other than
229 ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or
230 ``stderr=PIPE`` too.
231
Christian Heimes7f044312008-01-06 17:05:40 +0000232 .. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000233
Christian Heimes7f044312008-01-06 17:05:40 +0000234 The data read is buffered in memory, so do not use this method if the data
235 size is large or unlimited.
236
Georg Brandl116aa622007-08-15 14:28:22 +0000237
Christian Heimesa342c012008-04-20 21:01:16 +0000238.. method:: Popen.send_signal(signal)
239
240 Sends the signal *signal* to the child.
241
242 .. note::
243
244 On Windows only SIGTERM is supported so far. It's an alias for
245 :meth:`terminate`.
246
Christian Heimesa342c012008-04-20 21:01:16 +0000247
248.. method:: Popen.terminate()
249
250 Stop the child. On Posix OSs the method sends SIGTERM to the
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000251 child. On Windows the Win32 API function :cfunc:`TerminateProcess` is called
Christian Heimesa342c012008-04-20 21:01:16 +0000252 to stop the child.
253
Christian Heimesa342c012008-04-20 21:01:16 +0000254
255.. method:: Popen.kill()
256
257 Kills the child. On Posix OSs the function sends SIGKILL to the child.
258 On Windows :meth:`kill` is an alias for :meth:`terminate`.
259
Christian Heimesa342c012008-04-20 21:01:16 +0000260
Georg Brandl116aa622007-08-15 14:28:22 +0000261The following attributes are also available:
262
Georg Brandl116aa622007-08-15 14:28:22 +0000263.. attribute:: Popen.stdin
264
265 If the *stdin* argument is ``PIPE``, this attribute is a file object that
266 provides input to the child process. Otherwise, it is ``None``.
267
268
269.. attribute:: Popen.stdout
270
271 If the *stdout* argument is ``PIPE``, this attribute is a file object that
272 provides output from the child process. Otherwise, it is ``None``.
273
274
275.. attribute:: Popen.stderr
276
277 If the *stderr* argument is ``PIPE``, this attribute is file object that
278 provides error output from the child process. Otherwise, it is ``None``.
279
280
281.. attribute:: Popen.pid
282
283 The process ID of the child process.
284
285
286.. attribute:: Popen.returncode
287
Christian Heimes7f044312008-01-06 17:05:40 +0000288 The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly
289 by :meth:`communicate`). A ``None`` value indicates that the process
290 hasn't terminated yet.
291
292 A negative value ``-N`` indicates that the child was terminated by signal
293 ``N`` (Unix only).
Georg Brandl116aa622007-08-15 14:28:22 +0000294
295
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000296.. _subprocess-replacements:
297
Georg Brandl116aa622007-08-15 14:28:22 +0000298Replacing Older Functions with the subprocess Module
299----------------------------------------------------
300
301In this section, "a ==> b" means that b can be used as a replacement for a.
302
303.. note::
304
305 All functions in this section fail (more or less) silently if the executed
306 program cannot be found; this module raises an :exc:`OSError` exception.
307
308In the following examples, we assume that the subprocess module is imported with
309"from subprocess import \*".
310
311
312Replacing /bin/sh shell backquote
313^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
314
315::
316
317 output=`mycmd myarg`
318 ==>
319 output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
320
321
322Replacing shell pipe line
323^^^^^^^^^^^^^^^^^^^^^^^^^
324
325::
326
327 output=`dmesg | grep hda`
328 ==>
329 p1 = Popen(["dmesg"], stdout=PIPE)
330 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
331 output = p2.communicate()[0]
332
333
334Replacing os.system()
335^^^^^^^^^^^^^^^^^^^^^
336
337::
338
339 sts = os.system("mycmd" + " myarg")
340 ==>
341 p = Popen("mycmd" + " myarg", shell=True)
342 sts = os.waitpid(p.pid, 0)
343
344Notes:
345
346* Calling the program through the shell is usually not required.
347
348* It's easier to look at the :attr:`returncode` attribute than the exit status.
349
350A more realistic example would look like this::
351
352 try:
353 retcode = call("mycmd" + " myarg", shell=True)
354 if retcode < 0:
Collin Winterc79461b2007-09-01 23:34:30 +0000355 print("Child was terminated by signal", -retcode, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000356 else:
Collin Winterc79461b2007-09-01 23:34:30 +0000357 print("Child returned", retcode, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000358 except OSError as e:
Collin Winterc79461b2007-09-01 23:34:30 +0000359 print("Execution failed:", e, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000360
361
362Replacing os.spawn\*
363^^^^^^^^^^^^^^^^^^^^
364
365P_NOWAIT example::
366
367 pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
368 ==>
369 pid = Popen(["/bin/mycmd", "myarg"]).pid
370
371P_WAIT example::
372
373 retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
374 ==>
375 retcode = call(["/bin/mycmd", "myarg"])
376
377Vector example::
378
379 os.spawnvp(os.P_NOWAIT, path, args)
380 ==>
381 Popen([path] + args[1:])
382
383Environment example::
384
385 os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
386 ==>
387 Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
388
389
390Replacing os.popen\*
391^^^^^^^^^^^^^^^^^^^^
392
393::
394
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000395 pipe = os.popen(cmd, 'r', bufsize)
Georg Brandl116aa622007-08-15 14:28:22 +0000396 ==>
397 pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
398
399::
400
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000401 pipe = os.popen(cmd, 'w', bufsize)
Georg Brandl116aa622007-08-15 14:28:22 +0000402 ==>
403 pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
404