blob: 5ac32df2df33f943cdd8375a3aea990ed2eb2f31 [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*
17 commands.*
18
19Information about how the :mod:`subprocess` module can be used to replace these
20modules and functions can be found in the following sections.
21
22
23Using the subprocess Module
24---------------------------
25
26This module defines one class called :class:`Popen`:
27
28
29.. 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)
30
31 Arguments are:
32
33 *args* should be a string, or a sequence of program arguments. The program to
34 execute is normally the first item in the args sequence or string, but can be
35 explicitly set by using the executable argument.
36
37 On Unix, with *shell=False* (default): In this case, the Popen class uses
38 :meth:`os.execvp` to execute the child program. *args* should normally be a
39 sequence. A string will be treated as a sequence with the string as the only
40 item (the program to execute).
41
42 On Unix, with *shell=True*: If args is a string, it specifies the command string
43 to execute through the shell. If *args* is a sequence, the first item specifies
44 the command string, and any additional items will be treated as additional shell
45 arguments.
46
47 On Windows: the :class:`Popen` class uses CreateProcess() to execute the child
48 program, which operates on strings. If *args* is a sequence, it will be
49 converted to a string using the :meth:`list2cmdline` method. Please note that
50 not all MS Windows applications interpret the command line the same way:
51 :meth:`list2cmdline` is designed for applications using the same rules as the MS
52 C runtime.
53
54 *bufsize*, if given, has the same meaning as the corresponding argument to the
55 built-in open() function: :const:`0` means unbuffered, :const:`1` means line
56 buffered, any other positive value means use a buffer of (approximately) that
57 size. A negative *bufsize* means to use the system default, which usually means
58 fully buffered. The default value for *bufsize* is :const:`0` (unbuffered).
59
60 The *executable* argument specifies the program to execute. It is very seldom
61 needed: Usually, the program to execute is defined by the *args* argument. If
62 ``shell=True``, the *executable* argument specifies which shell to use. On Unix,
63 the default shell is :file:`/bin/sh`. On Windows, the default shell is
64 specified by the :envvar:`COMSPEC` environment variable.
65
66 *stdin*, *stdout* and *stderr* specify the executed programs' standard input,
67 standard output and standard error file handles, respectively. Valid values are
68 ``PIPE``, an existing file descriptor (a positive integer), an existing file
69 object, and ``None``. ``PIPE`` indicates that a new pipe to the child should be
70 created. With ``None``, no redirection will occur; the child's file handles
71 will be inherited from the parent. Additionally, *stderr* can be ``STDOUT``,
72 which indicates that the stderr data from the applications should be captured
73 into the same file handle as for stdout.
74
75 If *preexec_fn* is set to a callable object, this object will be called in the
76 child process just before the child is executed. (Unix only)
77
78 If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and
79 :const:`2` will be closed before the child process is executed. (Unix only).
80 Or, on Windows, if *close_fds* is true then no handles will be inherited by the
81 child process. Note that on Windows, you cannot set *close_fds* to true and
82 also redirect the standard handles by setting *stdin*, *stdout* or *stderr*.
83
84 If *shell* is :const:`True`, the specified command will be executed through the
85 shell.
86
87 If *cwd* is not ``None``, the child's current directory will be changed to *cwd*
88 before it is executed. Note that this directory is not considered when
89 searching the executable, so you can't specify the program's path relative to
90 *cwd*.
91
92 If *env* is not ``None``, it defines the environment variables for the new
93 process.
94
95 If *universal_newlines* is :const:`True`, the file objects stdout and stderr are
96 opened as text files, but lines may be terminated by any of ``'\n'``, the Unix
97 end-of-line convention, ``'\r'``, the Macintosh convention or ``'\r\n'``, the
98 Windows convention. All of these external representations are seen as ``'\n'``
99 by the Python program.
100
101 .. note::
102
103 This feature is only available if Python is built with universal newline support
104 (the default). Also, the newlines attribute of the file objects :attr:`stdout`,
105 :attr:`stdin` and :attr:`stderr` are not updated by the communicate() method.
106
107 The *startupinfo* and *creationflags*, if given, will be passed to the
108 underlying CreateProcess() function. They can specify things such as appearance
109 of the main window and priority for the new process. (Windows only)
110
111
112Convenience Functions
113^^^^^^^^^^^^^^^^^^^^^
114
115This module also defines two shortcut functions:
116
117
118.. function:: call(*popenargs, **kwargs)
119
120 Run command with arguments. Wait for command to complete, then return the
121 :attr:`returncode` attribute.
122
123 The arguments are the same as for the Popen constructor. Example::
124
125 retcode = call(["ls", "-l"])
126
127
128.. function:: check_call(*popenargs, **kwargs)
129
130 Run command with arguments. Wait for command to complete. If the exit code was
131 zero then return, otherwise raise :exc:`CalledProcessError.` The
132 :exc:`CalledProcessError` object will have the return code in the
133 :attr:`returncode` attribute.
134
135 The arguments are the same as for the Popen constructor. Example::
136
137 check_call(["ls", "-l"])
138
Georg Brandl116aa622007-08-15 14:28:22 +0000139
140Exceptions
141^^^^^^^^^^
142
143Exceptions raised in the child process, before the new program has started to
144execute, will be re-raised in the parent. Additionally, the exception object
145will have one extra attribute called :attr:`child_traceback`, which is a string
146containing traceback information from the childs point of view.
147
148The most common exception raised is :exc:`OSError`. This occurs, for example,
149when trying to execute a non-existent file. Applications should prepare for
150:exc:`OSError` exceptions.
151
152A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid
153arguments.
154
155check_call() will raise :exc:`CalledProcessError`, if the called process returns
156a non-zero return code.
157
158
159Security
160^^^^^^^^
161
162Unlike some other popen functions, this implementation will never call /bin/sh
163implicitly. This means that all characters, including shell metacharacters, can
164safely be passed to child processes.
165
166
167Popen Objects
168-------------
169
170Instances of the :class:`Popen` class have the following methods:
171
172
173.. method:: Popen.poll()
174
175 Check if child process has terminated. Returns returncode attribute.
176
177
178.. method:: Popen.wait()
179
180 Wait for child process to terminate. Returns returncode attribute.
181
182
183.. method:: Popen.communicate(input=None)
184
185 Interact with process: Send data to stdin. Read data from stdout and stderr,
186 until end-of-file is reached. Wait for process to terminate. The optional
187 *input* argument should be a string to be sent to the child process, or
188 ``None``, if no data should be sent to the child.
189
190 communicate() returns a tuple (stdout, stderr).
191
192 .. note::
193
194 The data read is buffered in memory, so do not use this method if the data size
195 is large or unlimited.
196
197The following attributes are also available:
198
199
200.. attribute:: Popen.stdin
201
202 If the *stdin* argument is ``PIPE``, this attribute is a file object that
203 provides input to the child process. Otherwise, it is ``None``.
204
205
206.. attribute:: Popen.stdout
207
208 If the *stdout* argument is ``PIPE``, this attribute is a file object that
209 provides output from the child process. Otherwise, it is ``None``.
210
211
212.. attribute:: Popen.stderr
213
214 If the *stderr* argument is ``PIPE``, this attribute is file object that
215 provides error output from the child process. Otherwise, it is ``None``.
216
217
218.. attribute:: Popen.pid
219
220 The process ID of the child process.
221
222
223.. attribute:: Popen.returncode
224
225 The child return code. A ``None`` value indicates that the process hasn't
226 terminated yet. A negative value -N indicates that the child was terminated by
227 signal N (Unix only).
228
229
230Replacing Older Functions with the subprocess Module
231----------------------------------------------------
232
233In this section, "a ==> b" means that b can be used as a replacement for a.
234
235.. note::
236
237 All functions in this section fail (more or less) silently if the executed
238 program cannot be found; this module raises an :exc:`OSError` exception.
239
240In the following examples, we assume that the subprocess module is imported with
241"from subprocess import \*".
242
243
244Replacing /bin/sh shell backquote
245^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
246
247::
248
249 output=`mycmd myarg`
250 ==>
251 output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
252
253
254Replacing shell pipe line
255^^^^^^^^^^^^^^^^^^^^^^^^^
256
257::
258
259 output=`dmesg | grep hda`
260 ==>
261 p1 = Popen(["dmesg"], stdout=PIPE)
262 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
263 output = p2.communicate()[0]
264
265
266Replacing os.system()
267^^^^^^^^^^^^^^^^^^^^^
268
269::
270
271 sts = os.system("mycmd" + " myarg")
272 ==>
273 p = Popen("mycmd" + " myarg", shell=True)
274 sts = os.waitpid(p.pid, 0)
275
276Notes:
277
278* Calling the program through the shell is usually not required.
279
280* It's easier to look at the :attr:`returncode` attribute than the exit status.
281
282A more realistic example would look like this::
283
284 try:
285 retcode = call("mycmd" + " myarg", shell=True)
286 if retcode < 0:
Collin Winterc79461b2007-09-01 23:34:30 +0000287 print("Child was terminated by signal", -retcode, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000288 else:
Collin Winterc79461b2007-09-01 23:34:30 +0000289 print("Child returned", retcode, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000290 except OSError as e:
Collin Winterc79461b2007-09-01 23:34:30 +0000291 print("Execution failed:", e, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000292
293
294Replacing os.spawn\*
295^^^^^^^^^^^^^^^^^^^^
296
297P_NOWAIT example::
298
299 pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
300 ==>
301 pid = Popen(["/bin/mycmd", "myarg"]).pid
302
303P_WAIT example::
304
305 retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
306 ==>
307 retcode = call(["/bin/mycmd", "myarg"])
308
309Vector example::
310
311 os.spawnvp(os.P_NOWAIT, path, args)
312 ==>
313 Popen([path] + args[1:])
314
315Environment example::
316
317 os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
318 ==>
319 Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
320
321
322Replacing os.popen\*
323^^^^^^^^^^^^^^^^^^^^
324
325::
326
327 pipe = os.popen(cmd, mode='r', bufsize)
328 ==>
329 pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
330
331::
332
333 pipe = os.popen(cmd, mode='w', bufsize)
334 ==>
335 pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
336