blob: 1c8a79c29189310be7c2cd17fdf1cf9f94d209c3 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`subprocess` --- Subprocess management
2===========================================
3
4.. module:: subprocess
5 :synopsis: Subprocess management.
6.. moduleauthor:: Peter Åstrand <astrand@lysator.liu.se>
7.. sectionauthor:: Peter Åstrand <astrand@lysator.liu.se>
8
9
Georg Brandl116aa622007-08-15 14:28:22 +000010The :mod:`subprocess` module allows you to spawn new processes, connect to their
11input/output/error pipes, and obtain their return codes. This module intends to
12replace several other, older modules and functions, such as::
13
14 os.system
15 os.spawn*
Georg Brandl116aa622007-08-15 14:28:22 +000016
17Information about how the :mod:`subprocess` module can be used to replace these
18modules and functions can be found in the following sections.
19
Benjamin Peterson41181742008-07-02 20:22:54 +000020.. seealso::
21
22 :pep:`324` -- PEP proposing the subprocess module
23
Georg Brandl116aa622007-08-15 14:28:22 +000024
25Using the subprocess Module
26---------------------------
27
28This module defines one class called :class:`Popen`:
29
30
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000031.. 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, restore_signals=True, start_new_session=False)
Georg Brandl116aa622007-08-15 14:28:22 +000032
33 Arguments are:
34
Benjamin Petersond18de0e2008-07-31 20:21:46 +000035 *args* should be a string, or a sequence of program arguments. The program
Benjamin Petersonfa0d7032009-06-01 22:42:33 +000036 to execute is normally the first item in the args sequence or the string if
37 a string is given, but can be explicitly set by using the *executable*
38 argument. When *executable* is given, the first item in the args sequence
39 is still treated by most programs as the command name, which can then be
40 different from the actual executable name. On Unix, it becomes the display
41 name for the executing program in utilities such as :program:`ps`.
Georg Brandl116aa622007-08-15 14:28:22 +000042
43 On Unix, with *shell=False* (default): In this case, the Popen class uses
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +000044 :meth:`os.execvp` like behavior to execute the child program.
45 *args* should normally be a
R. David Murray5973e4d2010-02-04 16:41:57 +000046 sequence. If a string is specified for *args*, it will be used as the name
47 or path of the program to execute; this will only work if the program is
48 being given no arguments.
Georg Brandl116aa622007-08-15 14:28:22 +000049
R. David Murray5973e4d2010-02-04 16:41:57 +000050 .. note::
51
52 :meth:`shlex.split` can be useful when determining the correct
53 tokenization for *args*, especially in complex cases::
54
55 >>> import shlex, subprocess
R. David Murray73bc75b2010-02-05 16:25:12 +000056 >>> command_line = input()
R. David Murray5973e4d2010-02-04 16:41:57 +000057 /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
58 >>> args = shlex.split(command_line)
59 >>> print(args)
60 ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
61 >>> p = subprocess.Popen(args) # Success!
62
63 Note in particular that options (such as *-input*) and arguments (such
64 as *eggs.txt*) that are separated by whitespace in the shell go in separate
65 list elements, while arguments that need quoting or backslash escaping when
66 used in the shell (such as filenames containing spaces or the *echo* command
67 shown above) are single list elements.
68
69 On Unix, with *shell=True*: If args is a string, it specifies the command
70 string to execute through the shell. This means that the string must be
71 formatted exactly as it would be when typed at the shell prompt. This
72 includes, for example, quoting or backslash escaping filenames with spaces in
73 them. If *args* is a sequence, the first item specifies the command string, and
74 any additional items will be treated as additional arguments to the shell
75 itself. That is to say, *Popen* does the equivalent of::
76
77 Popen(['/bin/sh', '-c', args[0], args[1], ...])
Georg Brandl116aa622007-08-15 14:28:22 +000078
79 On Windows: the :class:`Popen` class uses CreateProcess() to execute the child
80 program, which operates on strings. If *args* is a sequence, it will be
81 converted to a string using the :meth:`list2cmdline` method. Please note that
82 not all MS Windows applications interpret the command line the same way:
83 :meth:`list2cmdline` is designed for applications using the same rules as the MS
84 C runtime.
85
86 *bufsize*, if given, has the same meaning as the corresponding argument to the
87 built-in open() function: :const:`0` means unbuffered, :const:`1` means line
88 buffered, any other positive value means use a buffer of (approximately) that
89 size. A negative *bufsize* means to use the system default, which usually means
90 fully buffered. The default value for *bufsize* is :const:`0` (unbuffered).
91
Antoine Pitrou4b876202010-06-02 17:10:49 +000092 .. note::
93
94 If you experience performance issues, it is recommended that you try to
95 enable buffering by setting *bufsize* to either -1 or a large enough
96 positive value (such as 4096).
97
Georg Brandl116aa622007-08-15 14:28:22 +000098 The *executable* argument specifies the program to execute. It is very seldom
99 needed: Usually, the program to execute is defined by the *args* argument. If
100 ``shell=True``, the *executable* argument specifies which shell to use. On Unix,
101 the default shell is :file:`/bin/sh`. On Windows, the default shell is
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000102 specified by the :envvar:`COMSPEC` environment variable. The only reason you
103 would need to specify ``shell=True`` on Windows is where the command you
104 wish to execute is actually built in to the shell, eg ``dir``, ``copy``.
105 You don't need ``shell=True`` to run a batch file, nor to run a console-based
106 executable.
Georg Brandl116aa622007-08-15 14:28:22 +0000107
108 *stdin*, *stdout* and *stderr* specify the executed programs' standard input,
Georg Brandlaf265f42008-12-07 15:06:20 +0000109 standard output and standard error file handles, respectively. Valid values
110 are :data:`PIPE`, an existing file descriptor (a positive integer), an
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000111 existing :term:`file object`, and ``None``. :data:`PIPE` indicates that a
112 new pipe to the child should be created. With ``None``, no redirection will
113 occur; the child's file handles will be inherited from the parent. Additionally,
Georg Brandlaf265f42008-12-07 15:06:20 +0000114 *stderr* can be :data:`STDOUT`, which indicates that the stderr data from the
115 applications should be captured into the same file handle as for stdout.
Georg Brandl116aa622007-08-15 14:28:22 +0000116
117 If *preexec_fn* is set to a callable object, this object will be called in the
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000118 child process just before the child is executed.
119 (Unix only)
120
121 .. warning::
122
123 The *preexec_fn* parameter is not safe to use in the presence of threads
124 in your application. The child process could deadlock before exec is
125 called.
126 If you must use it, keep it trivial! Minimize the number of libraries
127 you call into.
128
129 .. note::
130
131 If you need to modify the environment for the child use the *env*
132 parameter rather than doing it in a *preexec_fn*.
133 The *start_new_session* parameter can take the place of a previously
134 common use of *preexec_fn* to call os.setsid() in the child.
Georg Brandl116aa622007-08-15 14:28:22 +0000135
136 If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and
137 :const:`2` will be closed before the child process is executed. (Unix only).
138 Or, on Windows, if *close_fds* is true then no handles will be inherited by the
139 child process. Note that on Windows, you cannot set *close_fds* to true and
140 also redirect the standard handles by setting *stdin*, *stdout* or *stderr*.
141
142 If *shell* is :const:`True`, the specified command will be executed through the
143 shell.
144
145 If *cwd* is not ``None``, the child's current directory will be changed to *cwd*
146 before it is executed. Note that this directory is not considered when
147 searching the executable, so you can't specify the program's path relative to
148 *cwd*.
149
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000150 If *restore_signals* is True (the default) all signals that Python has set to
151 SIG_IGN are restored to SIG_DFL in the child process before the exec.
152 Currently this includes the SIGPIPE, SIGXFZ and SIGXFSZ signals.
153 (Unix only)
154
155 .. versionchanged:: 3.2
156 *restore_signals* was added.
157
158 If *start_new_session* is True the setsid() system call will be made in the
159 child process prior to the execution of the subprocess. (Unix only)
160
161 .. versionchanged:: 3.2
162 *start_new_session* was added.
163
Christian Heimesa342c012008-04-20 21:01:16 +0000164 If *env* is not ``None``, it must be a mapping that defines the environment
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +0000165 variables for the new process; these are used instead of the default
166 behavior of inheriting the current process' environment.
Georg Brandl116aa622007-08-15 14:28:22 +0000167
R. David Murray1055e892009-04-16 18:15:32 +0000168 .. note::
R. David Murrayf4ac1492009-04-15 22:35:15 +0000169
Georg Brandl2708f3a2009-12-20 14:38:23 +0000170 If specified, *env* must provide any variables required for the program to
171 execute. On Windows, in order to run a `side-by-side assembly`_ the
172 specified *env* **must** include a valid :envvar:`SystemRoot`.
R. David Murrayf4ac1492009-04-15 22:35:15 +0000173
R. David Murray1055e892009-04-16 18:15:32 +0000174 .. _side-by-side assembly: http://en.wikipedia.org/wiki/Side-by-Side_Assembly
175
Georg Brandl116aa622007-08-15 14:28:22 +0000176 If *universal_newlines* is :const:`True`, the file objects stdout and stderr are
177 opened as text files, but lines may be terminated by any of ``'\n'``, the Unix
Georg Brandlc575c902008-09-13 17:46:05 +0000178 end-of-line convention, ``'\r'``, the old Macintosh convention or ``'\r\n'``, the
Georg Brandl116aa622007-08-15 14:28:22 +0000179 Windows convention. All of these external representations are seen as ``'\n'``
180 by the Python program.
181
182 .. note::
183
Georg Brandl7f01a132009-09-16 15:58:14 +0000184 This feature is only available if Python is built with universal newline
185 support (the default). Also, the newlines attribute of the file objects
186 :attr:`stdout`, :attr:`stdin` and :attr:`stderr` are not updated by the
187 :meth:`communicate` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000188
189 The *startupinfo* and *creationflags*, if given, will be passed to the
190 underlying CreateProcess() function. They can specify things such as appearance
191 of the main window and priority for the new process. (Windows only)
192
193
Georg Brandlaf265f42008-12-07 15:06:20 +0000194.. data:: PIPE
195
196 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
197 to :class:`Popen` and indicates that a pipe to the standard stream should be
198 opened.
199
200
201.. data:: STDOUT
202
203 Special value that can be used as the *stderr* argument to :class:`Popen` and
204 indicates that standard error should go into the same handle as standard
205 output.
Georg Brandl48310cd2009-01-03 21:18:54 +0000206
Georg Brandlaf265f42008-12-07 15:06:20 +0000207
Georg Brandl116aa622007-08-15 14:28:22 +0000208Convenience Functions
209^^^^^^^^^^^^^^^^^^^^^
210
Brett Cannona23810f2008-05-26 19:04:21 +0000211This module also defines four shortcut functions:
Georg Brandl116aa622007-08-15 14:28:22 +0000212
213
214.. function:: call(*popenargs, **kwargs)
215
216 Run command with arguments. Wait for command to complete, then return the
217 :attr:`returncode` attribute.
218
Benjamin Peterson21896a32010-03-21 22:03:03 +0000219 The arguments are the same as for the :class:`Popen` constructor. Example::
Georg Brandl116aa622007-08-15 14:28:22 +0000220
Georg Brandl2708f3a2009-12-20 14:38:23 +0000221 >>> retcode = subprocess.call(["ls", "-l"])
Georg Brandl116aa622007-08-15 14:28:22 +0000222
Philip Jenveyab7481a2009-05-22 05:46:35 +0000223 .. warning::
224
Philip Jenveyb0896842009-12-03 02:29:36 +0000225 Like :meth:`Popen.wait`, this will deadlock when using
226 ``stdout=PIPE`` and/or ``stderr=PIPE`` and the child process
227 generates enough output to a pipe such that it blocks waiting
228 for the OS pipe buffer to accept more data.
Philip Jenveyab7481a2009-05-22 05:46:35 +0000229
Georg Brandl116aa622007-08-15 14:28:22 +0000230
231.. function:: check_call(*popenargs, **kwargs)
232
233 Run command with arguments. Wait for command to complete. If the exit code was
Benjamin Petersone5384b02008-10-04 22:00:42 +0000234 zero then return, otherwise raise :exc:`CalledProcessError`. The
Georg Brandl116aa622007-08-15 14:28:22 +0000235 :exc:`CalledProcessError` object will have the return code in the
236 :attr:`returncode` attribute.
237
Benjamin Peterson21896a32010-03-21 22:03:03 +0000238 The arguments are the same as for the :class:`Popen` constructor. Example::
Georg Brandl116aa622007-08-15 14:28:22 +0000239
Georg Brandl2708f3a2009-12-20 14:38:23 +0000240 >>> subprocess.check_call(["ls", "-l"])
241 0
Georg Brandl116aa622007-08-15 14:28:22 +0000242
Philip Jenveyab7481a2009-05-22 05:46:35 +0000243 .. warning::
244
245 See the warning for :func:`call`.
246
Georg Brandl116aa622007-08-15 14:28:22 +0000247
Georg Brandlf9734072008-12-07 15:30:06 +0000248.. function:: check_output(*popenargs, **kwargs)
249
250 Run command with arguments and return its output as a byte string.
251
Benjamin Petersonaa069002009-01-23 03:26:36 +0000252 If the exit code was non-zero it raises a :exc:`CalledProcessError`. The
253 :exc:`CalledProcessError` object will have the return code in the
254 :attr:`returncode`
255 attribute and output in the :attr:`output` attribute.
Georg Brandlf9734072008-12-07 15:30:06 +0000256
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000257 The arguments are the same as for the :class:`Popen` constructor. Example::
Georg Brandlf9734072008-12-07 15:30:06 +0000258
259 >>> subprocess.check_output(["ls", "-l", "/dev/null"])
Georg Brandl2708f3a2009-12-20 14:38:23 +0000260 b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000261
262 The stdout argument is not allowed as it is used internally.
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000263 To capture standard error in the result, use ``stderr=subprocess.STDOUT``::
Georg Brandlf9734072008-12-07 15:30:06 +0000264
265 >>> subprocess.check_output(
Georg Brandl2708f3a2009-12-20 14:38:23 +0000266 ... ["/bin/sh", "-c", "ls non_existent_file; exit 0"],
267 ... stderr=subprocess.STDOUT)
268 b'ls: non_existent_file: No such file or directory\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000269
270 .. versionadded:: 3.1
271
272
Brett Cannona23810f2008-05-26 19:04:21 +0000273.. function:: getstatusoutput(cmd)
274 Return ``(status, output)`` of executing *cmd* in a shell.
275
276 Execute the string *cmd* in a shell with :func:`os.popen` and return a 2-tuple
277 ``(status, output)``. *cmd* is actually run as ``{ cmd ; } 2>&1``, so that the
278 returned output will contain output or error messages. A trailing newline is
279 stripped from the output. The exit status for the command can be interpreted
280 according to the rules for the C function :cfunc:`wait`. Example::
281
Brett Cannona23810f2008-05-26 19:04:21 +0000282 >>> subprocess.getstatusoutput('ls /bin/ls')
283 (0, '/bin/ls')
284 >>> subprocess.getstatusoutput('cat /bin/junk')
285 (256, 'cat: /bin/junk: No such file or directory')
286 >>> subprocess.getstatusoutput('/bin/junk')
287 (256, 'sh: /bin/junk: not found')
288
Georg Brandl7d418902008-12-27 19:08:11 +0000289 Availability: UNIX.
290
Brett Cannona23810f2008-05-26 19:04:21 +0000291
292.. function:: getoutput(cmd)
Georg Brandlf9734072008-12-07 15:30:06 +0000293 Return output (stdout and stderr) of executing *cmd* in a shell.
Brett Cannona23810f2008-05-26 19:04:21 +0000294
295 Like :func:`getstatusoutput`, except the exit status is ignored and the return
296 value is a string containing the command's output. Example::
297
Brett Cannona23810f2008-05-26 19:04:21 +0000298 >>> subprocess.getoutput('ls /bin/ls')
299 '/bin/ls'
300
Georg Brandl7d418902008-12-27 19:08:11 +0000301 Availability: UNIX.
302
Brett Cannona23810f2008-05-26 19:04:21 +0000303
Georg Brandl116aa622007-08-15 14:28:22 +0000304Exceptions
305^^^^^^^^^^
306
307Exceptions raised in the child process, before the new program has started to
308execute, will be re-raised in the parent. Additionally, the exception object
309will have one extra attribute called :attr:`child_traceback`, which is a string
Georg Brandl81675612010-08-26 14:30:56 +0000310containing traceback information from the child's point of view.
Georg Brandl116aa622007-08-15 14:28:22 +0000311
312The most common exception raised is :exc:`OSError`. This occurs, for example,
313when trying to execute a non-existent file. Applications should prepare for
314:exc:`OSError` exceptions.
315
316A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid
317arguments.
318
319check_call() will raise :exc:`CalledProcessError`, if the called process returns
320a non-zero return code.
321
322
323Security
324^^^^^^^^
325
326Unlike some other popen functions, this implementation will never call /bin/sh
327implicitly. This means that all characters, including shell metacharacters, can
328safely be passed to child processes.
329
330
331Popen Objects
332-------------
333
334Instances of the :class:`Popen` class have the following methods:
335
336
337.. method:: Popen.poll()
338
Christian Heimes7f044312008-01-06 17:05:40 +0000339 Check if child process has terminated. Set and return :attr:`returncode`
340 attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000341
342
343.. method:: Popen.wait()
344
Christian Heimes7f044312008-01-06 17:05:40 +0000345 Wait for child process to terminate. Set and return :attr:`returncode`
346 attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000347
Georg Brandl734e2682008-08-12 08:18:18 +0000348 .. warning::
349
Philip Jenveyb0896842009-12-03 02:29:36 +0000350 This will deadlock when using ``stdout=PIPE`` and/or
351 ``stderr=PIPE`` and the child process generates enough output to
352 a pipe such that it blocks waiting for the OS pipe buffer to
353 accept more data. Use :meth:`communicate` to avoid that.
Georg Brandl734e2682008-08-12 08:18:18 +0000354
Georg Brandl116aa622007-08-15 14:28:22 +0000355
356.. method:: Popen.communicate(input=None)
357
358 Interact with process: Send data to stdin. Read data from stdout and stderr,
359 until end-of-file is reached. Wait for process to terminate. The optional
Georg Brandle11787a2008-07-01 19:10:52 +0000360 *input* argument should be a byte string to be sent to the child process, or
Georg Brandl116aa622007-08-15 14:28:22 +0000361 ``None``, if no data should be sent to the child.
362
Georg Brandlaf265f42008-12-07 15:06:20 +0000363 :meth:`communicate` returns a tuple ``(stdoutdata, stderrdata)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000364
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000365 Note that if you want to send data to the process's stdin, you need to create
366 the Popen object with ``stdin=PIPE``. Similarly, to get anything other than
367 ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or
368 ``stderr=PIPE`` too.
369
Christian Heimes7f044312008-01-06 17:05:40 +0000370 .. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000371
Christian Heimes7f044312008-01-06 17:05:40 +0000372 The data read is buffered in memory, so do not use this method if the data
373 size is large or unlimited.
374
Georg Brandl116aa622007-08-15 14:28:22 +0000375
Christian Heimesa342c012008-04-20 21:01:16 +0000376.. method:: Popen.send_signal(signal)
377
378 Sends the signal *signal* to the child.
379
380 .. note::
381
Brian Curtineb24d742010-04-12 17:16:38 +0000382 On Windows, SIGTERM is an alias for :meth:`terminate`. CTRL_C_EVENT and
383 CTRL_BREAK_EVENT can be sent to processes started with a `creationflags`
384 parameter which includes `CREATE_NEW_PROCESS_GROUP`.
Christian Heimesa342c012008-04-20 21:01:16 +0000385
Christian Heimesa342c012008-04-20 21:01:16 +0000386
387.. method:: Popen.terminate()
388
389 Stop the child. On Posix OSs the method sends SIGTERM to the
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000390 child. On Windows the Win32 API function :cfunc:`TerminateProcess` is called
Christian Heimesa342c012008-04-20 21:01:16 +0000391 to stop the child.
392
Christian Heimesa342c012008-04-20 21:01:16 +0000393
394.. method:: Popen.kill()
395
396 Kills the child. On Posix OSs the function sends SIGKILL to the child.
397 On Windows :meth:`kill` is an alias for :meth:`terminate`.
398
Christian Heimesa342c012008-04-20 21:01:16 +0000399
Georg Brandl116aa622007-08-15 14:28:22 +0000400The following attributes are also available:
401
Georg Brandl734e2682008-08-12 08:18:18 +0000402.. warning::
403
Georg Brandle720c0a2009-04-27 16:20:50 +0000404 Use :meth:`communicate` rather than :attr:`.stdin.write <stdin>`,
405 :attr:`.stdout.read <stdout>` or :attr:`.stderr.read <stderr>` to avoid
406 deadlocks due to any of the other OS pipe buffers filling up and blocking the
407 child process.
Georg Brandl734e2682008-08-12 08:18:18 +0000408
409
Georg Brandl116aa622007-08-15 14:28:22 +0000410.. attribute:: Popen.stdin
411
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000412 If the *stdin* argument was :data:`PIPE`, this attribute is a :term:`file
413 object` that provides input to the child process. Otherwise, it is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000414
415
416.. attribute:: Popen.stdout
417
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000418 If the *stdout* argument was :data:`PIPE`, this attribute is a :term:`file
419 object` that provides output from the child process. Otherwise, it is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000420
421
422.. attribute:: Popen.stderr
423
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000424 If the *stderr* argument was :data:`PIPE`, this attribute is a :term:`file
425 object` that provides error output from the child process. Otherwise, it is
Georg Brandlaf265f42008-12-07 15:06:20 +0000426 ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000427
428
429.. attribute:: Popen.pid
430
431 The process ID of the child process.
432
Georg Brandl58bfdca2010-03-21 09:50:49 +0000433 Note that if you set the *shell* argument to ``True``, this is the process ID
434 of the spawned shell.
435
Georg Brandl116aa622007-08-15 14:28:22 +0000436
437.. attribute:: Popen.returncode
438
Christian Heimes7f044312008-01-06 17:05:40 +0000439 The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly
440 by :meth:`communicate`). A ``None`` value indicates that the process
441 hasn't terminated yet.
Georg Brandl48310cd2009-01-03 21:18:54 +0000442
Christian Heimes7f044312008-01-06 17:05:40 +0000443 A negative value ``-N`` indicates that the child was terminated by signal
444 ``N`` (Unix only).
Georg Brandl116aa622007-08-15 14:28:22 +0000445
446
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000447.. _subprocess-replacements:
448
Georg Brandl116aa622007-08-15 14:28:22 +0000449Replacing Older Functions with the subprocess Module
450----------------------------------------------------
451
452In this section, "a ==> b" means that b can be used as a replacement for a.
453
454.. note::
455
456 All functions in this section fail (more or less) silently if the executed
457 program cannot be found; this module raises an :exc:`OSError` exception.
458
459In the following examples, we assume that the subprocess module is imported with
460"from subprocess import \*".
461
462
463Replacing /bin/sh shell backquote
464^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
465
466::
467
468 output=`mycmd myarg`
469 ==>
470 output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
471
472
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000473Replacing shell pipeline
474^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000475
476::
477
478 output=`dmesg | grep hda`
479 ==>
480 p1 = Popen(["dmesg"], stdout=PIPE)
481 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
482 output = p2.communicate()[0]
483
484
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000485Replacing :func:`os.system`
486^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000487
488::
489
490 sts = os.system("mycmd" + " myarg")
491 ==>
492 p = Popen("mycmd" + " myarg", shell=True)
Alexandre Vassalottie52e3782009-07-17 09:18:18 +0000493 sts = os.waitpid(p.pid, 0)[1]
Georg Brandl116aa622007-08-15 14:28:22 +0000494
495Notes:
496
497* Calling the program through the shell is usually not required.
498
499* It's easier to look at the :attr:`returncode` attribute than the exit status.
500
501A more realistic example would look like this::
502
503 try:
504 retcode = call("mycmd" + " myarg", shell=True)
505 if retcode < 0:
Collin Winterc79461b2007-09-01 23:34:30 +0000506 print("Child was terminated by signal", -retcode, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000507 else:
Collin Winterc79461b2007-09-01 23:34:30 +0000508 print("Child returned", retcode, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000509 except OSError as e:
Collin Winterc79461b2007-09-01 23:34:30 +0000510 print("Execution failed:", e, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000511
512
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000513Replacing the :func:`os.spawn <os.spawnl>` family
514^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000515
516P_NOWAIT example::
517
518 pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
519 ==>
520 pid = Popen(["/bin/mycmd", "myarg"]).pid
521
522P_WAIT example::
523
524 retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
525 ==>
526 retcode = call(["/bin/mycmd", "myarg"])
527
528Vector example::
529
530 os.spawnvp(os.P_NOWAIT, path, args)
531 ==>
532 Popen([path] + args[1:])
533
534Environment example::
535
536 os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
537 ==>
538 Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
539
540
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000541
542Replacing :func:`os.popen`, :func:`os.popen2`, :func:`os.popen3`
543^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000544
545::
546
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000547 (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
Georg Brandl116aa622007-08-15 14:28:22 +0000548 ==>
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000549 p = Popen(cmd, shell=True, bufsize=bufsize,
550 stdin=PIPE, stdout=PIPE, close_fds=True)
551 (child_stdin, child_stdout) = (p.stdin, p.stdout)
Georg Brandl116aa622007-08-15 14:28:22 +0000552
553::
554
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000555 (child_stdin,
556 child_stdout,
557 child_stderr) = os.popen3(cmd, mode, bufsize)
Georg Brandl116aa622007-08-15 14:28:22 +0000558 ==>
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000559 p = Popen(cmd, shell=True, bufsize=bufsize,
560 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
561 (child_stdin,
562 child_stdout,
563 child_stderr) = (p.stdin, p.stdout, p.stderr)
564
565::
566
567 (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
568 ==>
569 p = Popen(cmd, shell=True, bufsize=bufsize,
570 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
571 (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
572
573Return code handling translates as follows::
574
575 pipe = os.popen(cmd, 'w')
576 ...
577 rc = pipe.close()
Stefan Krahfc9e08d2010-07-14 10:16:11 +0000578 if rc is not None and rc >> 8:
Ezio Melotti985e24d2009-09-13 07:54:02 +0000579 print("There were some errors")
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000580 ==>
581 process = Popen(cmd, 'w', stdin=PIPE)
582 ...
583 process.stdin.close()
584 if process.wait() != 0:
Ezio Melotti985e24d2009-09-13 07:54:02 +0000585 print("There were some errors")
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000586
587
588Replacing functions from the :mod:`popen2` module
589^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
590
591.. note::
592
593 If the cmd argument to popen2 functions is a string, the command is executed
594 through /bin/sh. If it is a list, the command is directly executed.
595
596::
597
598 (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
599 ==>
600 p = Popen(["somestring"], shell=True, bufsize=bufsize,
601 stdin=PIPE, stdout=PIPE, close_fds=True)
602 (child_stdout, child_stdin) = (p.stdout, p.stdin)
603
604::
605
606 (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
607 ==>
608 p = Popen(["mycmd", "myarg"], bufsize=bufsize,
609 stdin=PIPE, stdout=PIPE, close_fds=True)
610 (child_stdout, child_stdin) = (p.stdout, p.stdin)
611
612:class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as
613:class:`subprocess.Popen`, except that:
614
615* :class:`Popen` raises an exception if the execution fails.
616
617* the *capturestderr* argument is replaced with the *stderr* argument.
618
619* ``stdin=PIPE`` and ``stdout=PIPE`` must be specified.
620
621* popen2 closes all file descriptors by default, but you have to specify
622 ``close_fds=True`` with :class:`Popen`.