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