blob: 7402ad57fd7d1deeeb815bccfb62468a54fbefab [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
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
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
44 :meth:`os.execvp` to execute the child program. *args* should normally be a
R. David Murray13cc4fd2010-02-04 16:44:31 +000045 sequence. If a string is specified for *args*, it will be used as the name
46 or path of the program to execute; this will only work if the program is
47 being given no arguments.
Georg Brandl116aa622007-08-15 14:28:22 +000048
R. David Murray13cc4fd2010-02-04 16:44:31 +000049 .. note::
50
51 :meth:`shlex.split` can be useful when determining the correct
52 tokenization for *args*, especially in complex cases::
53
54 >>> import shlex, subprocess
R. David Murray2c4f8d12010-02-05 16:26:37 +000055 >>> command_line = input()
R. David Murray13cc4fd2010-02-04 16:44:31 +000056 /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
57 >>> args = shlex.split(command_line)
58 >>> print(args)
59 ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
60 >>> p = subprocess.Popen(args) # Success!
61
62 Note in particular that options (such as *-input*) and arguments (such
63 as *eggs.txt*) that are separated by whitespace in the shell go in separate
64 list elements, while arguments that need quoting or backslash escaping when
65 used in the shell (such as filenames containing spaces or the *echo* command
66 shown above) are single list elements.
67
68 On Unix, with *shell=True*: If args is a string, it specifies the command
69 string to execute through the shell. This means that the string must be
70 formatted exactly as it would be when typed at the shell prompt. This
71 includes, for example, quoting or backslash escaping filenames with spaces in
72 them. If *args* is a sequence, the first item specifies the command string, and
73 any additional items will be treated as additional arguments to the shell
74 itself. That is to say, *Popen* does the equivalent of::
75
76 Popen(['/bin/sh', '-c', args[0], args[1], ...])
Georg Brandl116aa622007-08-15 14:28:22 +000077
78 On Windows: the :class:`Popen` class uses CreateProcess() to execute the child
79 program, which operates on strings. If *args* is a sequence, it will be
80 converted to a string using the :meth:`list2cmdline` method. Please note that
81 not all MS Windows applications interpret the command line the same way:
82 :meth:`list2cmdline` is designed for applications using the same rules as the MS
83 C runtime.
84
85 *bufsize*, if given, has the same meaning as the corresponding argument to the
86 built-in open() function: :const:`0` means unbuffered, :const:`1` means line
87 buffered, any other positive value means use a buffer of (approximately) that
88 size. A negative *bufsize* means to use the system default, which usually means
89 fully buffered. The default value for *bufsize* is :const:`0` (unbuffered).
90
Antoine Pitrou5050bb22010-06-02 17:11:32 +000091 .. note::
92
93 If you experience performance issues, it is recommended that you try to
94 enable buffering by setting *bufsize* to either -1 or a large enough
95 positive value (such as 4096).
96
Georg Brandl116aa622007-08-15 14:28:22 +000097 The *executable* argument specifies the program to execute. It is very seldom
98 needed: Usually, the program to execute is defined by the *args* argument. If
99 ``shell=True``, the *executable* argument specifies which shell to use. On Unix,
100 the default shell is :file:`/bin/sh`. On Windows, the default shell is
Georg Brandlbcc484e2009-08-13 11:51:54 +0000101 specified by the :envvar:`COMSPEC` environment variable. The only reason you
102 would need to specify ``shell=True`` on Windows is where the command you
103 wish to execute is actually built in to the shell, eg ``dir``, ``copy``.
104 You don't need ``shell=True`` to run a batch file, nor to run a console-based
105 executable.
Georg Brandl116aa622007-08-15 14:28:22 +0000106
107 *stdin*, *stdout* and *stderr* specify the executed programs' standard input,
Georg Brandlaf265f42008-12-07 15:06:20 +0000108 standard output and standard error file handles, respectively. Valid values
109 are :data:`PIPE`, an existing file descriptor (a positive integer), an
Antoine Pitrou25d535e2010-09-15 11:25:11 +0000110 existing :term:`file object`, and ``None``. :data:`PIPE` indicates that a
111 new pipe to the child should be created. With ``None``, no redirection will
112 occur; the child's file handles will be inherited from the parent. Additionally,
Georg Brandlaf265f42008-12-07 15:06:20 +0000113 *stderr* can be :data:`STDOUT`, which indicates that the stderr data from the
114 applications should be captured into the same file handle as for stdout.
Georg Brandl116aa622007-08-15 14:28:22 +0000115
116 If *preexec_fn* is set to a callable object, this object will be called in the
117 child process just before the child is executed. (Unix only)
118
119 If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and
120 :const:`2` will be closed before the child process is executed. (Unix only).
121 Or, on Windows, if *close_fds* is true then no handles will be inherited by the
122 child process. Note that on Windows, you cannot set *close_fds* to true and
123 also redirect the standard handles by setting *stdin*, *stdout* or *stderr*.
124
125 If *shell* is :const:`True`, the specified command will be executed through the
126 shell.
127
128 If *cwd* is not ``None``, the child's current directory will be changed to *cwd*
129 before it is executed. Note that this directory is not considered when
130 searching the executable, so you can't specify the program's path relative to
131 *cwd*.
132
Christian Heimesa342c012008-04-20 21:01:16 +0000133 If *env* is not ``None``, it must be a mapping that defines the environment
134 variables for the new process; these are used instead of inheriting the current
135 process' environment, which is the default behavior.
Georg Brandl116aa622007-08-15 14:28:22 +0000136
R. David Murray1055e892009-04-16 18:15:32 +0000137 .. note::
R. David Murrayf4ac1492009-04-15 22:35:15 +0000138
Georg Brandl8ffe0bc2010-10-06 07:17:29 +0000139 If specified, *env* must provide any variables required for the program to
140 execute. On Windows, in order to run a `side-by-side assembly`_ the
141 specified *env* **must** include a valid :envvar:`SystemRoot`.
R. David Murrayf4ac1492009-04-15 22:35:15 +0000142
R. David Murray1055e892009-04-16 18:15:32 +0000143 .. _side-by-side assembly: http://en.wikipedia.org/wiki/Side-by-Side_Assembly
144
Georg Brandl116aa622007-08-15 14:28:22 +0000145 If *universal_newlines* is :const:`True`, the file objects stdout and stderr are
146 opened as text files, but lines may be terminated by any of ``'\n'``, the Unix
Georg Brandlc575c902008-09-13 17:46:05 +0000147 end-of-line convention, ``'\r'``, the old Macintosh convention or ``'\r\n'``, the
Georg Brandl116aa622007-08-15 14:28:22 +0000148 Windows convention. All of these external representations are seen as ``'\n'``
149 by the Python program.
150
151 .. note::
152
Georg Brandlb044b2a2009-09-16 16:05:59 +0000153 This feature is only available if Python is built with universal newline
154 support (the default). Also, the newlines attribute of the file objects
155 :attr:`stdout`, :attr:`stdin` and :attr:`stderr` are not updated by the
156 :meth:`communicate` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000157
158 The *startupinfo* and *creationflags*, if given, will be passed to the
159 underlying CreateProcess() function. They can specify things such as appearance
160 of the main window and priority for the new process. (Windows only)
161
162
Georg Brandlaf265f42008-12-07 15:06:20 +0000163.. data:: PIPE
164
165 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
166 to :class:`Popen` and indicates that a pipe to the standard stream should be
167 opened.
168
169
170.. data:: STDOUT
171
172 Special value that can be used as the *stderr* argument to :class:`Popen` and
173 indicates that standard error should go into the same handle as standard
174 output.
Georg Brandl48310cd2009-01-03 21:18:54 +0000175
Georg Brandlaf265f42008-12-07 15:06:20 +0000176
Georg Brandl116aa622007-08-15 14:28:22 +0000177Convenience Functions
178^^^^^^^^^^^^^^^^^^^^^
179
Brett Cannona23810f2008-05-26 19:04:21 +0000180This module also defines four shortcut functions:
Georg Brandl116aa622007-08-15 14:28:22 +0000181
182
183.. function:: call(*popenargs, **kwargs)
184
185 Run command with arguments. Wait for command to complete, then return the
186 :attr:`returncode` attribute.
187
188 The arguments are the same as for the Popen constructor. Example::
189
Georg Brandl8ffe0bc2010-10-06 07:17:29 +0000190 >>> retcode = subprocess.call(["ls", "-l"])
Georg Brandl116aa622007-08-15 14:28:22 +0000191
Philip Jenveyab7481a2009-05-22 05:46:35 +0000192 .. warning::
193
194 Like :meth:`Popen.wait`, this will deadlock if the child process
195 generates enough output to a stdout or stderr pipe such that it blocks
196 waiting for the OS pipe buffer to accept more data.
197
Georg Brandl116aa622007-08-15 14:28:22 +0000198
199.. function:: check_call(*popenargs, **kwargs)
200
201 Run command with arguments. Wait for command to complete. If the exit code was
Benjamin Petersone5384b02008-10-04 22:00:42 +0000202 zero then return, otherwise raise :exc:`CalledProcessError`. The
Georg Brandl116aa622007-08-15 14:28:22 +0000203 :exc:`CalledProcessError` object will have the return code in the
204 :attr:`returncode` attribute.
205
206 The arguments are the same as for the Popen constructor. Example::
207
Georg Brandl8ffe0bc2010-10-06 07:17:29 +0000208 >>> subprocess.check_call(["ls", "-l"])
209 0
Georg Brandl116aa622007-08-15 14:28:22 +0000210
Philip Jenveyab7481a2009-05-22 05:46:35 +0000211 .. warning::
212
213 See the warning for :func:`call`.
214
Georg Brandl116aa622007-08-15 14:28:22 +0000215
Georg Brandlf9734072008-12-07 15:30:06 +0000216.. function:: check_output(*popenargs, **kwargs)
217
218 Run command with arguments and return its output as a byte string.
219
Benjamin Petersonaa069002009-01-23 03:26:36 +0000220 If the exit code was non-zero it raises a :exc:`CalledProcessError`. The
221 :exc:`CalledProcessError` object will have the return code in the
222 :attr:`returncode`
223 attribute and output in the :attr:`output` attribute.
Georg Brandlf9734072008-12-07 15:30:06 +0000224
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000225 The arguments are the same as for the :class:`Popen` constructor. Example::
Georg Brandlf9734072008-12-07 15:30:06 +0000226
227 >>> subprocess.check_output(["ls", "-l", "/dev/null"])
Georg Brandl8ffe0bc2010-10-06 07:17:29 +0000228 b'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000229
230 The stdout argument is not allowed as it is used internally.
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000231 To capture standard error in the result, use ``stderr=subprocess.STDOUT``::
Georg Brandlf9734072008-12-07 15:30:06 +0000232
233 >>> subprocess.check_output(
Georg Brandl8ffe0bc2010-10-06 07:17:29 +0000234 ... ["/bin/sh", "-c", "ls non_existent_file; exit 0"],
235 ... stderr=subprocess.STDOUT)
236 b'ls: non_existent_file: No such file or directory\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000237
238 .. versionadded:: 3.1
239
240
Brett Cannona23810f2008-05-26 19:04:21 +0000241.. function:: getstatusoutput(cmd)
Georg Brandld098c3d2010-10-06 10:38:58 +0000242
Brett Cannona23810f2008-05-26 19:04:21 +0000243 Return ``(status, output)`` of executing *cmd* in a shell.
244
245 Execute the string *cmd* in a shell with :func:`os.popen` and return a 2-tuple
246 ``(status, output)``. *cmd* is actually run as ``{ cmd ; } 2>&1``, so that the
247 returned output will contain output or error messages. A trailing newline is
248 stripped from the output. The exit status for the command can be interpreted
249 according to the rules for the C function :cfunc:`wait`. Example::
250
Brett Cannona23810f2008-05-26 19:04:21 +0000251 >>> subprocess.getstatusoutput('ls /bin/ls')
252 (0, '/bin/ls')
253 >>> subprocess.getstatusoutput('cat /bin/junk')
254 (256, 'cat: /bin/junk: No such file or directory')
255 >>> subprocess.getstatusoutput('/bin/junk')
256 (256, 'sh: /bin/junk: not found')
257
Georg Brandl7d418902008-12-27 19:08:11 +0000258 Availability: UNIX.
259
Brett Cannona23810f2008-05-26 19:04:21 +0000260
261.. function:: getoutput(cmd)
Georg Brandld098c3d2010-10-06 10:38:58 +0000262
Georg Brandlf9734072008-12-07 15:30:06 +0000263 Return output (stdout and stderr) of executing *cmd* in a shell.
Brett Cannona23810f2008-05-26 19:04:21 +0000264
265 Like :func:`getstatusoutput`, except the exit status is ignored and the return
266 value is a string containing the command's output. Example::
267
Brett Cannona23810f2008-05-26 19:04:21 +0000268 >>> subprocess.getoutput('ls /bin/ls')
269 '/bin/ls'
270
Georg Brandl7d418902008-12-27 19:08:11 +0000271 Availability: UNIX.
272
Brett Cannona23810f2008-05-26 19:04:21 +0000273
Georg Brandl116aa622007-08-15 14:28:22 +0000274Exceptions
275^^^^^^^^^^
276
277Exceptions raised in the child process, before the new program has started to
278execute, will be re-raised in the parent. Additionally, the exception object
279will have one extra attribute called :attr:`child_traceback`, which is a string
Georg Brandl57a5e3f2010-10-06 08:54:16 +0000280containing traceback information from the child's point of view.
Georg Brandl116aa622007-08-15 14:28:22 +0000281
282The most common exception raised is :exc:`OSError`. This occurs, for example,
283when trying to execute a non-existent file. Applications should prepare for
284:exc:`OSError` exceptions.
285
286A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid
287arguments.
288
289check_call() will raise :exc:`CalledProcessError`, if the called process returns
290a non-zero return code.
291
292
293Security
294^^^^^^^^
295
296Unlike some other popen functions, this implementation will never call /bin/sh
297implicitly. This means that all characters, including shell metacharacters, can
298safely be passed to child processes.
299
300
301Popen Objects
302-------------
303
304Instances of the :class:`Popen` class have the following methods:
305
306
307.. method:: Popen.poll()
308
Christian Heimes7f044312008-01-06 17:05:40 +0000309 Check if child process has terminated. Set and return :attr:`returncode`
310 attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000311
312
313.. method:: Popen.wait()
314
Christian Heimes7f044312008-01-06 17:05:40 +0000315 Wait for child process to terminate. Set and return :attr:`returncode`
316 attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000317
Georg Brandl734e2682008-08-12 08:18:18 +0000318 .. warning::
319
320 This will deadlock if the child process generates enough output to a
321 stdout or stderr pipe such that it blocks waiting for the OS pipe buffer
322 to accept more data. Use :meth:`communicate` to avoid that.
323
Georg Brandl116aa622007-08-15 14:28:22 +0000324
325.. method:: Popen.communicate(input=None)
326
327 Interact with process: Send data to stdin. Read data from stdout and stderr,
328 until end-of-file is reached. Wait for process to terminate. The optional
Georg Brandle11787a2008-07-01 19:10:52 +0000329 *input* argument should be a byte string to be sent to the child process, or
Georg Brandl116aa622007-08-15 14:28:22 +0000330 ``None``, if no data should be sent to the child.
331
Georg Brandlaf265f42008-12-07 15:06:20 +0000332 :meth:`communicate` returns a tuple ``(stdoutdata, stderrdata)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000333
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000334 Note that if you want to send data to the process's stdin, you need to create
335 the Popen object with ``stdin=PIPE``. Similarly, to get anything other than
336 ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or
337 ``stderr=PIPE`` too.
338
Christian Heimes7f044312008-01-06 17:05:40 +0000339 .. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000340
Christian Heimes7f044312008-01-06 17:05:40 +0000341 The data read is buffered in memory, so do not use this method if the data
342 size is large or unlimited.
343
Georg Brandl116aa622007-08-15 14:28:22 +0000344
Christian Heimesa342c012008-04-20 21:01:16 +0000345.. method:: Popen.send_signal(signal)
346
347 Sends the signal *signal* to the child.
348
349 .. note::
350
351 On Windows only SIGTERM is supported so far. It's an alias for
352 :meth:`terminate`.
353
Christian Heimesa342c012008-04-20 21:01:16 +0000354
355.. method:: Popen.terminate()
356
357 Stop the child. On Posix OSs the method sends SIGTERM to the
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000358 child. On Windows the Win32 API function :cfunc:`TerminateProcess` is called
Christian Heimesa342c012008-04-20 21:01:16 +0000359 to stop the child.
360
Christian Heimesa342c012008-04-20 21:01:16 +0000361
362.. method:: Popen.kill()
363
364 Kills the child. On Posix OSs the function sends SIGKILL to the child.
365 On Windows :meth:`kill` is an alias for :meth:`terminate`.
366
Christian Heimesa342c012008-04-20 21:01:16 +0000367
Georg Brandl116aa622007-08-15 14:28:22 +0000368The following attributes are also available:
369
Georg Brandl734e2682008-08-12 08:18:18 +0000370.. warning::
371
Georg Brandle720c0a2009-04-27 16:20:50 +0000372 Use :meth:`communicate` rather than :attr:`.stdin.write <stdin>`,
373 :attr:`.stdout.read <stdout>` or :attr:`.stderr.read <stderr>` to avoid
374 deadlocks due to any of the other OS pipe buffers filling up and blocking the
375 child process.
Georg Brandl734e2682008-08-12 08:18:18 +0000376
377
Georg Brandl116aa622007-08-15 14:28:22 +0000378.. attribute:: Popen.stdin
379
Antoine Pitrou25d535e2010-09-15 11:25:11 +0000380 If the *stdin* argument was :data:`PIPE`, this attribute is a :term:`file
381 object` that provides input to the child process. Otherwise, it is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000382
383
384.. attribute:: Popen.stdout
385
Antoine Pitrou25d535e2010-09-15 11:25:11 +0000386 If the *stdout* argument was :data:`PIPE`, this attribute is a :term:`file
387 object` that provides output from the child process. Otherwise, it is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000388
389
390.. attribute:: Popen.stderr
391
Antoine Pitrou25d535e2010-09-15 11:25:11 +0000392 If the *stderr* argument was :data:`PIPE`, this attribute is a :term:`file
393 object` that provides error output from the child process. Otherwise, it is
Georg Brandlaf265f42008-12-07 15:06:20 +0000394 ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000395
396
397.. attribute:: Popen.pid
398
399 The process ID of the child process.
400
Georg Brandl16215c72010-10-06 07:59:52 +0000401 Note that if you set the *shell* argument to ``True``, this is the process ID
402 of the spawned shell.
403
Georg Brandl116aa622007-08-15 14:28:22 +0000404
405.. attribute:: Popen.returncode
406
Christian Heimes7f044312008-01-06 17:05:40 +0000407 The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly
408 by :meth:`communicate`). A ``None`` value indicates that the process
409 hasn't terminated yet.
Georg Brandl48310cd2009-01-03 21:18:54 +0000410
Christian Heimes7f044312008-01-06 17:05:40 +0000411 A negative value ``-N`` indicates that the child was terminated by signal
412 ``N`` (Unix only).
Georg Brandl116aa622007-08-15 14:28:22 +0000413
414
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000415.. _subprocess-replacements:
416
Georg Brandl116aa622007-08-15 14:28:22 +0000417Replacing Older Functions with the subprocess Module
418----------------------------------------------------
419
420In this section, "a ==> b" means that b can be used as a replacement for a.
421
422.. note::
423
424 All functions in this section fail (more or less) silently if the executed
425 program cannot be found; this module raises an :exc:`OSError` exception.
426
427In the following examples, we assume that the subprocess module is imported with
428"from subprocess import \*".
429
430
431Replacing /bin/sh shell backquote
432^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
433
434::
435
436 output=`mycmd myarg`
437 ==>
438 output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
439
440
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000441Replacing shell pipeline
442^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000443
444::
445
446 output=`dmesg | grep hda`
447 ==>
448 p1 = Popen(["dmesg"], stdout=PIPE)
449 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
450 output = p2.communicate()[0]
451
452
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000453Replacing :func:`os.system`
454^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000455
456::
457
458 sts = os.system("mycmd" + " myarg")
459 ==>
460 p = Popen("mycmd" + " myarg", shell=True)
Georg Brandld80344f2009-08-13 12:26:19 +0000461 sts = os.waitpid(p.pid, 0)[1]
Georg Brandl116aa622007-08-15 14:28:22 +0000462
463Notes:
464
465* Calling the program through the shell is usually not required.
466
467* It's easier to look at the :attr:`returncode` attribute than the exit status.
468
469A more realistic example would look like this::
470
471 try:
472 retcode = call("mycmd" + " myarg", shell=True)
473 if retcode < 0:
Collin Winterc79461b2007-09-01 23:34:30 +0000474 print("Child was terminated by signal", -retcode, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000475 else:
Collin Winterc79461b2007-09-01 23:34:30 +0000476 print("Child returned", retcode, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000477 except OSError as e:
Collin Winterc79461b2007-09-01 23:34:30 +0000478 print("Execution failed:", e, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000479
480
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000481Replacing the :func:`os.spawn <os.spawnl>` family
482^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000483
484P_NOWAIT example::
485
486 pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
487 ==>
488 pid = Popen(["/bin/mycmd", "myarg"]).pid
489
490P_WAIT example::
491
492 retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
493 ==>
494 retcode = call(["/bin/mycmd", "myarg"])
495
496Vector example::
497
498 os.spawnvp(os.P_NOWAIT, path, args)
499 ==>
500 Popen([path] + args[1:])
501
502Environment example::
503
504 os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
505 ==>
506 Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
507
508
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000509
510Replacing :func:`os.popen`, :func:`os.popen2`, :func:`os.popen3`
511^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000512
513::
514
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000515 (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
Georg Brandl116aa622007-08-15 14:28:22 +0000516 ==>
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000517 p = Popen(cmd, shell=True, bufsize=bufsize,
518 stdin=PIPE, stdout=PIPE, close_fds=True)
519 (child_stdin, child_stdout) = (p.stdin, p.stdout)
Georg Brandl116aa622007-08-15 14:28:22 +0000520
521::
522
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000523 (child_stdin,
524 child_stdout,
525 child_stderr) = os.popen3(cmd, mode, bufsize)
Georg Brandl116aa622007-08-15 14:28:22 +0000526 ==>
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000527 p = Popen(cmd, shell=True, bufsize=bufsize,
528 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
529 (child_stdin,
530 child_stdout,
531 child_stderr) = (p.stdin, p.stdout, p.stderr)
532
533::
534
535 (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
536 ==>
537 p = Popen(cmd, shell=True, bufsize=bufsize,
538 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
539 (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
540
541Return code handling translates as follows::
542
543 pipe = os.popen(cmd, 'w')
544 ...
545 rc = pipe.close()
Stefan Krah5a5031f2010-07-14 10:19:40 +0000546 if rc is not None and rc >> 8:
Ezio Melotti713e0422009-09-13 08:13:21 +0000547 print("There were some errors")
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000548 ==>
549 process = Popen(cmd, 'w', stdin=PIPE)
550 ...
551 process.stdin.close()
552 if process.wait() != 0:
Ezio Melotti713e0422009-09-13 08:13:21 +0000553 print("There were some errors")
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000554
555
556Replacing functions from the :mod:`popen2` module
557^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
558
559.. note::
560
561 If the cmd argument to popen2 functions is a string, the command is executed
562 through /bin/sh. If it is a list, the command is directly executed.
563
564::
565
566 (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
567 ==>
568 p = Popen(["somestring"], shell=True, bufsize=bufsize,
569 stdin=PIPE, stdout=PIPE, close_fds=True)
570 (child_stdout, child_stdin) = (p.stdout, p.stdin)
571
572::
573
574 (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
575 ==>
576 p = Popen(["mycmd", "myarg"], bufsize=bufsize,
577 stdin=PIPE, stdout=PIPE, close_fds=True)
578 (child_stdout, child_stdin) = (p.stdout, p.stdin)
579
580:class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as
581:class:`subprocess.Popen`, except that:
582
583* :class:`Popen` raises an exception if the execution fails.
584
585* the *capturestderr* argument is replaced with the *stderr* argument.
586
587* ``stdin=PIPE`` and ``stdout=PIPE`` must be specified.
588
589* popen2 closes all file descriptors by default, but you have to specify
590 ``close_fds=True`` with :class:`Popen`.