blob: 2344bcb2f914bd27066295b17dfcfcff06a403c3 [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
Christian Heimesa342c012008-04-20 21:01:16 +000092 If *env* is not ``None``, it must be a mapping that defines the environment
93 variables for the new process; these are used instead of inheriting the current
94 process' environment, which is the default behavior.
Georg Brandl116aa622007-08-15 14:28:22 +000095
96 If *universal_newlines* is :const:`True`, the file objects stdout and stderr are
97 opened as text files, but lines may be terminated by any of ``'\n'``, the Unix
98 end-of-line convention, ``'\r'``, the Macintosh convention or ``'\r\n'``, the
99 Windows convention. All of these external representations are seen as ``'\n'``
100 by the Python program.
101
102 .. note::
103
104 This feature is only available if Python is built with universal newline support
105 (the default). Also, the newlines attribute of the file objects :attr:`stdout`,
106 :attr:`stdin` and :attr:`stderr` are not updated by the communicate() method.
107
108 The *startupinfo* and *creationflags*, if given, will be passed to the
109 underlying CreateProcess() function. They can specify things such as appearance
110 of the main window and priority for the new process. (Windows only)
111
112
113Convenience Functions
114^^^^^^^^^^^^^^^^^^^^^
115
116This module also defines two shortcut functions:
117
118
119.. function:: call(*popenargs, **kwargs)
120
121 Run command with arguments. Wait for command to complete, then return the
122 :attr:`returncode` attribute.
123
124 The arguments are the same as for the Popen constructor. Example::
125
126 retcode = call(["ls", "-l"])
127
128
129.. function:: check_call(*popenargs, **kwargs)
130
131 Run command with arguments. Wait for command to complete. If the exit code was
132 zero then return, otherwise raise :exc:`CalledProcessError.` The
133 :exc:`CalledProcessError` object will have the return code in the
134 :attr:`returncode` attribute.
135
136 The arguments are the same as for the Popen constructor. Example::
137
138 check_call(["ls", "-l"])
139
Georg Brandl116aa622007-08-15 14:28:22 +0000140
141Exceptions
142^^^^^^^^^^
143
144Exceptions raised in the child process, before the new program has started to
145execute, will be re-raised in the parent. Additionally, the exception object
146will have one extra attribute called :attr:`child_traceback`, which is a string
147containing traceback information from the childs point of view.
148
149The most common exception raised is :exc:`OSError`. This occurs, for example,
150when trying to execute a non-existent file. Applications should prepare for
151:exc:`OSError` exceptions.
152
153A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid
154arguments.
155
156check_call() will raise :exc:`CalledProcessError`, if the called process returns
157a non-zero return code.
158
159
160Security
161^^^^^^^^
162
163Unlike some other popen functions, this implementation will never call /bin/sh
164implicitly. This means that all characters, including shell metacharacters, can
165safely be passed to child processes.
166
167
168Popen Objects
169-------------
170
171Instances of the :class:`Popen` class have the following methods:
172
173
174.. method:: Popen.poll()
175
Christian Heimes7f044312008-01-06 17:05:40 +0000176 Check if child process has terminated. Set and return :attr:`returncode`
177 attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000178
179
180.. method:: Popen.wait()
181
Christian Heimes7f044312008-01-06 17:05:40 +0000182 Wait for child process to terminate. Set and return :attr:`returncode`
183 attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000184
185
186.. method:: Popen.communicate(input=None)
187
188 Interact with process: Send data to stdin. Read data from stdout and stderr,
189 until end-of-file is reached. Wait for process to terminate. The optional
190 *input* argument should be a string to be sent to the child process, or
191 ``None``, if no data should be sent to the child.
192
Christian Heimes7f044312008-01-06 17:05:40 +0000193 :meth:`communicate` returns a tuple ``(stdout, stderr)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000194
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000195 Note that if you want to send data to the process's stdin, you need to create
196 the Popen object with ``stdin=PIPE``. Similarly, to get anything other than
197 ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or
198 ``stderr=PIPE`` too.
199
Christian Heimes7f044312008-01-06 17:05:40 +0000200 .. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000201
Christian Heimes7f044312008-01-06 17:05:40 +0000202 The data read is buffered in memory, so do not use this method if the data
203 size is large or unlimited.
204
Georg Brandl116aa622007-08-15 14:28:22 +0000205
Christian Heimesa342c012008-04-20 21:01:16 +0000206.. method:: Popen.send_signal(signal)
207
208 Sends the signal *signal* to the child.
209
210 .. note::
211
212 On Windows only SIGTERM is supported so far. It's an alias for
213 :meth:`terminate`.
214
215 .. versionadded:: 2.6
216
217
218.. method:: Popen.terminate()
219
220 Stop the child. On Posix OSs the method sends SIGTERM to the
221 child. On Windows the Win32 API function TerminateProcess is called
222 to stop the child.
223
224 .. versionadded:: 2.6
225
226
227.. method:: Popen.kill()
228
229 Kills the child. On Posix OSs the function sends SIGKILL to the child.
230 On Windows :meth:`kill` is an alias for :meth:`terminate`.
231
232 .. versionadded:: 2.6
233
234
Georg Brandl116aa622007-08-15 14:28:22 +0000235The following attributes are also available:
236
Georg Brandl116aa622007-08-15 14:28:22 +0000237.. attribute:: Popen.stdin
238
239 If the *stdin* argument is ``PIPE``, this attribute is a file object that
240 provides input to the child process. Otherwise, it is ``None``.
241
242
243.. attribute:: Popen.stdout
244
245 If the *stdout* argument is ``PIPE``, this attribute is a file object that
246 provides output from the child process. Otherwise, it is ``None``.
247
248
249.. attribute:: Popen.stderr
250
251 If the *stderr* argument is ``PIPE``, this attribute is file object that
252 provides error output from the child process. Otherwise, it is ``None``.
253
254
255.. attribute:: Popen.pid
256
257 The process ID of the child process.
258
259
260.. attribute:: Popen.returncode
261
Christian Heimes7f044312008-01-06 17:05:40 +0000262 The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly
263 by :meth:`communicate`). A ``None`` value indicates that the process
264 hasn't terminated yet.
265
266 A negative value ``-N`` indicates that the child was terminated by signal
267 ``N`` (Unix only).
Georg Brandl116aa622007-08-15 14:28:22 +0000268
269
270Replacing Older Functions with the subprocess Module
271----------------------------------------------------
272
273In this section, "a ==> b" means that b can be used as a replacement for a.
274
275.. note::
276
277 All functions in this section fail (more or less) silently if the executed
278 program cannot be found; this module raises an :exc:`OSError` exception.
279
280In the following examples, we assume that the subprocess module is imported with
281"from subprocess import \*".
282
283
284Replacing /bin/sh shell backquote
285^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
286
287::
288
289 output=`mycmd myarg`
290 ==>
291 output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
292
293
294Replacing shell pipe line
295^^^^^^^^^^^^^^^^^^^^^^^^^
296
297::
298
299 output=`dmesg | grep hda`
300 ==>
301 p1 = Popen(["dmesg"], stdout=PIPE)
302 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
303 output = p2.communicate()[0]
304
305
306Replacing os.system()
307^^^^^^^^^^^^^^^^^^^^^
308
309::
310
311 sts = os.system("mycmd" + " myarg")
312 ==>
313 p = Popen("mycmd" + " myarg", shell=True)
314 sts = os.waitpid(p.pid, 0)
315
316Notes:
317
318* Calling the program through the shell is usually not required.
319
320* It's easier to look at the :attr:`returncode` attribute than the exit status.
321
322A more realistic example would look like this::
323
324 try:
325 retcode = call("mycmd" + " myarg", shell=True)
326 if retcode < 0:
Collin Winterc79461b2007-09-01 23:34:30 +0000327 print("Child was terminated by signal", -retcode, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000328 else:
Collin Winterc79461b2007-09-01 23:34:30 +0000329 print("Child returned", retcode, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000330 except OSError as e:
Collin Winterc79461b2007-09-01 23:34:30 +0000331 print("Execution failed:", e, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000332
333
334Replacing os.spawn\*
335^^^^^^^^^^^^^^^^^^^^
336
337P_NOWAIT example::
338
339 pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
340 ==>
341 pid = Popen(["/bin/mycmd", "myarg"]).pid
342
343P_WAIT example::
344
345 retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
346 ==>
347 retcode = call(["/bin/mycmd", "myarg"])
348
349Vector example::
350
351 os.spawnvp(os.P_NOWAIT, path, args)
352 ==>
353 Popen([path] + args[1:])
354
355Environment example::
356
357 os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
358 ==>
359 Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
360
361
362Replacing os.popen\*
363^^^^^^^^^^^^^^^^^^^^
364
365::
366
367 pipe = os.popen(cmd, mode='r', bufsize)
368 ==>
369 pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
370
371::
372
373 pipe = os.popen(cmd, mode='w', bufsize)
374 ==>
375 pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
376