blob: 02b8d59f663c49dfd3c27a5d04ebdb6261b9b5ce [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +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 os.popen*
20 popen2.*
21 commands.*
22
23Information about how the :mod:`subprocess` module can be used to replace these
24modules and functions can be found in the following sections.
25
Georg Brandl68b4e742008-07-01 19:59:00 +000026.. seealso::
27
28 :pep:`324` -- PEP proposing the subprocess module
29
Georg Brandl8ec7f652007-08-15 14:28:01 +000030
31Using the subprocess Module
32---------------------------
33
34This module defines one class called :class:`Popen`:
35
36
37.. 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)
38
39 Arguments are:
40
41 *args* should be a string, or a sequence of program arguments. The program to
42 execute is normally the first item in the args sequence or string, but can be
43 explicitly set by using the executable argument.
44
45 On Unix, with *shell=False* (default): In this case, the Popen class uses
46 :meth:`os.execvp` to execute the child program. *args* should normally be a
47 sequence. A string will be treated as a sequence with the string as the only
48 item (the program to execute).
49
50 On Unix, with *shell=True*: If args is a string, it specifies the command string
51 to execute through the shell. If *args* is a sequence, the first item specifies
52 the command string, and any additional items will be treated as additional shell
53 arguments.
54
55 On Windows: the :class:`Popen` class uses CreateProcess() to execute the child
56 program, which operates on strings. If *args* is a sequence, it will be
57 converted to a string using the :meth:`list2cmdline` method. Please note that
58 not all MS Windows applications interpret the command line the same way:
59 :meth:`list2cmdline` is designed for applications using the same rules as the MS
60 C runtime.
61
62 *bufsize*, if given, has the same meaning as the corresponding argument to the
63 built-in open() function: :const:`0` means unbuffered, :const:`1` means line
64 buffered, any other positive value means use a buffer of (approximately) that
65 size. A negative *bufsize* means to use the system default, which usually means
66 fully buffered. The default value for *bufsize* is :const:`0` (unbuffered).
67
68 The *executable* argument specifies the program to execute. It is very seldom
69 needed: Usually, the program to execute is defined by the *args* argument. If
70 ``shell=True``, the *executable* argument specifies which shell to use. On Unix,
71 the default shell is :file:`/bin/sh`. On Windows, the default shell is
72 specified by the :envvar:`COMSPEC` environment variable.
73
74 *stdin*, *stdout* and *stderr* specify the executed programs' standard input,
75 standard output and standard error file handles, respectively. Valid values are
76 ``PIPE``, an existing file descriptor (a positive integer), an existing file
77 object, and ``None``. ``PIPE`` indicates that a new pipe to the child should be
78 created. With ``None``, no redirection will occur; the child's file handles
79 will be inherited from the parent. Additionally, *stderr* can be ``STDOUT``,
80 which indicates that the stderr data from the applications should be captured
81 into the same file handle as for stdout.
82
83 If *preexec_fn* is set to a callable object, this object will be called in the
84 child process just before the child is executed. (Unix only)
85
86 If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and
87 :const:`2` will be closed before the child process is executed. (Unix only).
88 Or, on Windows, if *close_fds* is true then no handles will be inherited by the
89 child process. Note that on Windows, you cannot set *close_fds* to true and
90 also redirect the standard handles by setting *stdin*, *stdout* or *stderr*.
91
92 If *shell* is :const:`True`, the specified command will be executed through the
93 shell.
94
95 If *cwd* is not ``None``, the child's current directory will be changed to *cwd*
96 before it is executed. Note that this directory is not considered when
97 searching the executable, so you can't specify the program's path relative to
98 *cwd*.
99
Georg Brandlf801b0f2008-04-19 16:58:49 +0000100 If *env* is not ``None``, it must be a mapping that defines the environment
101 variables for the new process; these are used instead of inheriting the current
102 process' environment, which is the default behavior.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000103
104 If *universal_newlines* is :const:`True`, the file objects stdout and stderr are
105 opened as text files, but lines may be terminated by any of ``'\n'``, the Unix
106 end-of-line convention, ``'\r'``, the Macintosh convention or ``'\r\n'``, the
107 Windows convention. All of these external representations are seen as ``'\n'``
108 by the Python program.
109
110 .. note::
111
112 This feature is only available if Python is built with universal newline support
113 (the default). Also, the newlines attribute of the file objects :attr:`stdout`,
114 :attr:`stdin` and :attr:`stderr` are not updated by the communicate() method.
115
116 The *startupinfo* and *creationflags*, if given, will be passed to the
117 underlying CreateProcess() function. They can specify things such as appearance
118 of the main window and priority for the new process. (Windows only)
119
120
121Convenience Functions
122^^^^^^^^^^^^^^^^^^^^^
123
124This module also defines two shortcut functions:
125
126
127.. function:: call(*popenargs, **kwargs)
128
129 Run command with arguments. Wait for command to complete, then return the
130 :attr:`returncode` attribute.
131
132 The arguments are the same as for the Popen constructor. Example::
133
134 retcode = call(["ls", "-l"])
135
136
137.. function:: check_call(*popenargs, **kwargs)
138
139 Run command with arguments. Wait for command to complete. If the exit code was
140 zero then return, otherwise raise :exc:`CalledProcessError.` The
141 :exc:`CalledProcessError` object will have the return code in the
142 :attr:`returncode` attribute.
143
144 The arguments are the same as for the Popen constructor. Example::
145
146 check_call(["ls", "-l"])
147
148 .. versionadded:: 2.5
149
150
151Exceptions
152^^^^^^^^^^
153
154Exceptions raised in the child process, before the new program has started to
155execute, will be re-raised in the parent. Additionally, the exception object
156will have one extra attribute called :attr:`child_traceback`, which is a string
157containing traceback information from the childs point of view.
158
159The most common exception raised is :exc:`OSError`. This occurs, for example,
160when trying to execute a non-existent file. Applications should prepare for
161:exc:`OSError` exceptions.
162
163A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid
164arguments.
165
166check_call() will raise :exc:`CalledProcessError`, if the called process returns
167a non-zero return code.
168
169
170Security
171^^^^^^^^
172
173Unlike some other popen functions, this implementation will never call /bin/sh
174implicitly. This means that all characters, including shell metacharacters, can
175safely be passed to child processes.
176
177
178Popen Objects
179-------------
180
181Instances of the :class:`Popen` class have the following methods:
182
183
184.. method:: Popen.poll()
185
Georg Brandl2cb103f2008-01-06 16:01:26 +0000186 Check if child process has terminated. Set and return :attr:`returncode`
187 attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000188
189
190.. method:: Popen.wait()
191
Georg Brandl2cb103f2008-01-06 16:01:26 +0000192 Wait for child process to terminate. Set and return :attr:`returncode`
193 attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000194
195
196.. method:: Popen.communicate(input=None)
197
198 Interact with process: Send data to stdin. Read data from stdout and stderr,
199 until end-of-file is reached. Wait for process to terminate. The optional
200 *input* argument should be a string to be sent to the child process, or
201 ``None``, if no data should be sent to the child.
202
Georg Brandl2cb103f2008-01-06 16:01:26 +0000203 :meth:`communicate` returns a tuple ``(stdout, stderr)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000204
Georg Brandl439f2502007-11-24 11:31:46 +0000205 Note that if you want to send data to the process's stdin, you need to create
206 the Popen object with ``stdin=PIPE``. Similarly, to get anything other than
207 ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or
208 ``stderr=PIPE`` too.
209
Georg Brandl2cb103f2008-01-06 16:01:26 +0000210 .. note::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000211
Georg Brandl2cb103f2008-01-06 16:01:26 +0000212 The data read is buffered in memory, so do not use this method if the data
213 size is large or unlimited.
214
Georg Brandl8ec7f652007-08-15 14:28:01 +0000215
Christian Heimese74c8f22008-04-19 02:23:57 +0000216.. method:: Popen.send_signal(signal)
217
218 Sends the signal *signal* to the child.
219
220 .. note::
221
222 On Windows only SIGTERM is supported so far. It's an alias for
Georg Brandl734de682008-04-19 08:23:59 +0000223 :meth:`terminate`.
224
225 .. versionadded:: 2.6
Christian Heimese74c8f22008-04-19 02:23:57 +0000226
227
228.. method:: Popen.terminate()
229
230 Stop the child. On Posix OSs the method sends SIGTERM to the
Andrew M. Kuchling64c6a0e2008-04-21 02:08:00 +0000231 child. On Windows the Win32 API function :cfunc:`TerminateProcess` is called
Christian Heimese74c8f22008-04-19 02:23:57 +0000232 to stop the child.
233
Georg Brandl734de682008-04-19 08:23:59 +0000234 .. versionadded:: 2.6
235
Christian Heimese74c8f22008-04-19 02:23:57 +0000236
237.. method:: Popen.kill()
238
239 Kills the child. On Posix OSs the function sends SIGKILL to the child.
Georg Brandl734de682008-04-19 08:23:59 +0000240 On Windows :meth:`kill` is an alias for :meth:`terminate`.
241
242 .. versionadded:: 2.6
Christian Heimese74c8f22008-04-19 02:23:57 +0000243
244
Georg Brandl8ec7f652007-08-15 14:28:01 +0000245The following attributes are also available:
246
Georg Brandl8ec7f652007-08-15 14:28:01 +0000247.. attribute:: Popen.stdin
248
249 If the *stdin* argument is ``PIPE``, this attribute is a file object that
250 provides input to the child process. Otherwise, it is ``None``.
251
252
253.. attribute:: Popen.stdout
254
255 If the *stdout* argument is ``PIPE``, this attribute is a file object that
256 provides output from the child process. Otherwise, it is ``None``.
257
258
259.. attribute:: Popen.stderr
260
261 If the *stderr* argument is ``PIPE``, this attribute is file object that
262 provides error output from the child process. Otherwise, it is ``None``.
263
264
265.. attribute:: Popen.pid
266
267 The process ID of the child process.
268
269
270.. attribute:: Popen.returncode
271
Georg Brandl2cb103f2008-01-06 16:01:26 +0000272 The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly
273 by :meth:`communicate`). A ``None`` value indicates that the process
274 hasn't terminated yet.
275
276 A negative value ``-N`` indicates that the child was terminated by signal
277 ``N`` (Unix only).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000278
279
Georg Brandl0ba92b22008-06-22 09:05:29 +0000280.. _subprocess-replacements:
281
Georg Brandl8ec7f652007-08-15 14:28:01 +0000282Replacing Older Functions with the subprocess Module
283----------------------------------------------------
284
285In this section, "a ==> b" means that b can be used as a replacement for a.
286
287.. note::
288
289 All functions in this section fail (more or less) silently if the executed
290 program cannot be found; this module raises an :exc:`OSError` exception.
291
292In the following examples, we assume that the subprocess module is imported with
293"from subprocess import \*".
294
295
296Replacing /bin/sh shell backquote
297^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
298
299::
300
301 output=`mycmd myarg`
302 ==>
303 output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
304
305
306Replacing shell pipe line
307^^^^^^^^^^^^^^^^^^^^^^^^^
308
309::
310
311 output=`dmesg | grep hda`
312 ==>
313 p1 = Popen(["dmesg"], stdout=PIPE)
314 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
315 output = p2.communicate()[0]
316
317
318Replacing os.system()
319^^^^^^^^^^^^^^^^^^^^^
320
321::
322
323 sts = os.system("mycmd" + " myarg")
324 ==>
325 p = Popen("mycmd" + " myarg", shell=True)
326 sts = os.waitpid(p.pid, 0)
327
328Notes:
329
330* Calling the program through the shell is usually not required.
331
332* It's easier to look at the :attr:`returncode` attribute than the exit status.
333
334A more realistic example would look like this::
335
336 try:
337 retcode = call("mycmd" + " myarg", shell=True)
338 if retcode < 0:
339 print >>sys.stderr, "Child was terminated by signal", -retcode
340 else:
341 print >>sys.stderr, "Child returned", retcode
342 except OSError, e:
343 print >>sys.stderr, "Execution failed:", e
344
345
346Replacing os.spawn\*
347^^^^^^^^^^^^^^^^^^^^
348
349P_NOWAIT example::
350
351 pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
352 ==>
353 pid = Popen(["/bin/mycmd", "myarg"]).pid
354
355P_WAIT example::
356
357 retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
358 ==>
359 retcode = call(["/bin/mycmd", "myarg"])
360
361Vector example::
362
363 os.spawnvp(os.P_NOWAIT, path, args)
364 ==>
365 Popen([path] + args[1:])
366
367Environment example::
368
369 os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
370 ==>
371 Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
372
373
374Replacing os.popen\*
375^^^^^^^^^^^^^^^^^^^^
376
377::
378
Georg Brandl8bd05192008-06-22 18:11:52 +0000379 pipe = os.popen(cmd, 'r', bufsize)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000380 ==>
381 pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
382
383::
384
Georg Brandl8bd05192008-06-22 18:11:52 +0000385 pipe = os.popen(cmd, 'w', bufsize)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000386 ==>
387 pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
388
389::
390
391 (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
392 ==>
393 p = Popen(cmd, shell=True, bufsize=bufsize,
394 stdin=PIPE, stdout=PIPE, close_fds=True)
395 (child_stdin, child_stdout) = (p.stdin, p.stdout)
396
397::
398
399 (child_stdin,
400 child_stdout,
401 child_stderr) = os.popen3(cmd, mode, bufsize)
402 ==>
403 p = Popen(cmd, shell=True, bufsize=bufsize,
404 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
405 (child_stdin,
406 child_stdout,
407 child_stderr) = (p.stdin, p.stdout, p.stderr)
408
409::
410
411 (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
412 ==>
413 p = Popen(cmd, shell=True, bufsize=bufsize,
414 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
415 (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
416
417
418Replacing popen2.\*
419^^^^^^^^^^^^^^^^^^^
420
421.. note::
422
423 If the cmd argument to popen2 functions is a string, the command is executed
424 through /bin/sh. If it is a list, the command is directly executed.
425
426::
427
428 (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
429 ==>
430 p = Popen(["somestring"], shell=True, bufsize=bufsize,
431 stdin=PIPE, stdout=PIPE, close_fds=True)
432 (child_stdout, child_stdin) = (p.stdout, p.stdin)
433
434::
435
436 (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
437 ==>
438 p = Popen(["mycmd", "myarg"], bufsize=bufsize,
439 stdin=PIPE, stdout=PIPE, close_fds=True)
440 (child_stdout, child_stdin) = (p.stdout, p.stdin)
441
442The popen2.Popen3 and popen2.Popen4 basically works as subprocess.Popen, except
443that:
444
445* subprocess.Popen raises an exception if the execution fails
446
447* the *capturestderr* argument is replaced with the *stderr* argument.
448
449* stdin=PIPE and stdout=PIPE must be specified.
450
451* popen2 closes all file descriptors by default, but you have to specify
452 close_fds=True with subprocess.Popen.
453