blob: 93ad19c8f16cc0c0d939901042d26298bb268f18 [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
45 sequence. A string will be treated as a sequence with the string as the only
46 item (the program to execute).
47
48 On Unix, with *shell=True*: If args is a string, it specifies the command string
49 to execute through the shell. If *args* is a sequence, the first item specifies
50 the command string, and any additional items will be treated as additional shell
51 arguments.
52
53 On Windows: the :class:`Popen` class uses CreateProcess() to execute the child
54 program, which operates on strings. If *args* is a sequence, it will be
55 converted to a string using the :meth:`list2cmdline` method. Please note that
56 not all MS Windows applications interpret the command line the same way:
57 :meth:`list2cmdline` is designed for applications using the same rules as the MS
58 C runtime.
59
60 *bufsize*, if given, has the same meaning as the corresponding argument to the
61 built-in open() function: :const:`0` means unbuffered, :const:`1` means line
62 buffered, any other positive value means use a buffer of (approximately) that
63 size. A negative *bufsize* means to use the system default, which usually means
64 fully buffered. The default value for *bufsize* is :const:`0` (unbuffered).
65
66 The *executable* argument specifies the program to execute. It is very seldom
67 needed: Usually, the program to execute is defined by the *args* argument. If
68 ``shell=True``, the *executable* argument specifies which shell to use. On Unix,
69 the default shell is :file:`/bin/sh`. On Windows, the default shell is
Alexandre Vassalotti260484d2009-07-17 11:43:26 +000070 specified by the :envvar:`COMSPEC` environment variable. The only reason you
71 would need to specify ``shell=True`` on Windows is where the command you
72 wish to execute is actually built in to the shell, eg ``dir``, ``copy``.
73 You don't need ``shell=True`` to run a batch file, nor to run a console-based
74 executable.
Georg Brandl116aa622007-08-15 14:28:22 +000075
76 *stdin*, *stdout* and *stderr* specify the executed programs' standard input,
Georg Brandlaf265f42008-12-07 15:06:20 +000077 standard output and standard error file handles, respectively. Valid values
78 are :data:`PIPE`, an existing file descriptor (a positive integer), an
79 existing file object, and ``None``. :data:`PIPE` indicates that a new pipe
80 to the child should be created. With ``None``, no redirection will occur;
81 the child's file handles will be inherited from the parent. Additionally,
82 *stderr* can be :data:`STDOUT`, which indicates that the stderr data from the
83 applications should be captured into the same file handle as for stdout.
Georg Brandl116aa622007-08-15 14:28:22 +000084
85 If *preexec_fn* is set to a callable object, this object will be called in the
86 child process just before the child is executed. (Unix only)
87
88 If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and
89 :const:`2` will be closed before the child process is executed. (Unix only).
90 Or, on Windows, if *close_fds* is true then no handles will be inherited by the
91 child process. Note that on Windows, you cannot set *close_fds* to true and
92 also redirect the standard handles by setting *stdin*, *stdout* or *stderr*.
93
94 If *shell* is :const:`True`, the specified command will be executed through the
95 shell.
96
97 If *cwd* is not ``None``, the child's current directory will be changed to *cwd*
98 before it is executed. Note that this directory is not considered when
99 searching the executable, so you can't specify the program's path relative to
100 *cwd*.
101
Christian Heimesa342c012008-04-20 21:01:16 +0000102 If *env* is not ``None``, it must be a mapping that defines the environment
103 variables for the new process; these are used instead of inheriting the current
104 process' environment, which is the default behavior.
Georg Brandl116aa622007-08-15 14:28:22 +0000105
R. David Murray1055e892009-04-16 18:15:32 +0000106 .. note::
R. David Murrayf4ac1492009-04-15 22:35:15 +0000107
R. David Murray1055e892009-04-16 18:15:32 +0000108 If specified, *env* must provide any variables required
109 for the program to execute. On Windows, in order to run a
110 `side-by-side assembly`_ the specified *env* **must** include a valid
R. David Murrayf4ac1492009-04-15 22:35:15 +0000111 :envvar:`SystemRoot`.
112
R. David Murray1055e892009-04-16 18:15:32 +0000113 .. _side-by-side assembly: http://en.wikipedia.org/wiki/Side-by-Side_Assembly
114
Georg Brandl116aa622007-08-15 14:28:22 +0000115 If *universal_newlines* is :const:`True`, the file objects stdout and stderr are
116 opened as text files, but lines may be terminated by any of ``'\n'``, the Unix
Georg Brandlc575c902008-09-13 17:46:05 +0000117 end-of-line convention, ``'\r'``, the old Macintosh convention or ``'\r\n'``, the
Georg Brandl116aa622007-08-15 14:28:22 +0000118 Windows convention. All of these external representations are seen as ``'\n'``
119 by the Python program.
120
121 .. note::
122
Georg Brandl7f01a132009-09-16 15:58:14 +0000123 This feature is only available if Python is built with universal newline
124 support (the default). Also, the newlines attribute of the file objects
125 :attr:`stdout`, :attr:`stdin` and :attr:`stderr` are not updated by the
126 :meth:`communicate` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000127
128 The *startupinfo* and *creationflags*, if given, will be passed to the
129 underlying CreateProcess() function. They can specify things such as appearance
130 of the main window and priority for the new process. (Windows only)
131
132
Georg Brandlaf265f42008-12-07 15:06:20 +0000133.. data:: PIPE
134
135 Special value that can be used as the *stdin*, *stdout* or *stderr* argument
136 to :class:`Popen` and indicates that a pipe to the standard stream should be
137 opened.
138
139
140.. data:: STDOUT
141
142 Special value that can be used as the *stderr* argument to :class:`Popen` and
143 indicates that standard error should go into the same handle as standard
144 output.
Georg Brandl48310cd2009-01-03 21:18:54 +0000145
Georg Brandlaf265f42008-12-07 15:06:20 +0000146
Georg Brandl116aa622007-08-15 14:28:22 +0000147Convenience Functions
148^^^^^^^^^^^^^^^^^^^^^
149
Brett Cannona23810f2008-05-26 19:04:21 +0000150This module also defines four shortcut functions:
Georg Brandl116aa622007-08-15 14:28:22 +0000151
152
153.. function:: call(*popenargs, **kwargs)
154
155 Run command with arguments. Wait for command to complete, then return the
156 :attr:`returncode` attribute.
157
158 The arguments are the same as for the Popen constructor. Example::
159
160 retcode = call(["ls", "-l"])
161
Philip Jenveyab7481a2009-05-22 05:46:35 +0000162 .. warning::
163
Philip Jenveyb0896842009-12-03 02:29:36 +0000164 Like :meth:`Popen.wait`, this will deadlock when using
165 ``stdout=PIPE`` and/or ``stderr=PIPE`` and the child process
166 generates enough output to a pipe such that it blocks waiting
167 for the OS pipe buffer to accept more data.
Philip Jenveyab7481a2009-05-22 05:46:35 +0000168
Georg Brandl116aa622007-08-15 14:28:22 +0000169
170.. function:: check_call(*popenargs, **kwargs)
171
172 Run command with arguments. Wait for command to complete. If the exit code was
Benjamin Petersone5384b02008-10-04 22:00:42 +0000173 zero then return, otherwise raise :exc:`CalledProcessError`. The
Georg Brandl116aa622007-08-15 14:28:22 +0000174 :exc:`CalledProcessError` object will have the return code in the
175 :attr:`returncode` attribute.
176
177 The arguments are the same as for the Popen constructor. Example::
178
179 check_call(["ls", "-l"])
180
Philip Jenveyab7481a2009-05-22 05:46:35 +0000181 .. warning::
182
183 See the warning for :func:`call`.
184
Georg Brandl116aa622007-08-15 14:28:22 +0000185
Georg Brandlf9734072008-12-07 15:30:06 +0000186.. function:: check_output(*popenargs, **kwargs)
187
188 Run command with arguments and return its output as a byte string.
189
Benjamin Petersonaa069002009-01-23 03:26:36 +0000190 If the exit code was non-zero it raises a :exc:`CalledProcessError`. The
191 :exc:`CalledProcessError` object will have the return code in the
192 :attr:`returncode`
193 attribute and output in the :attr:`output` attribute.
Georg Brandlf9734072008-12-07 15:30:06 +0000194
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000195 The arguments are the same as for the :class:`Popen` constructor. Example::
Georg Brandlf9734072008-12-07 15:30:06 +0000196
197 >>> subprocess.check_output(["ls", "-l", "/dev/null"])
198 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
199
200 The stdout argument is not allowed as it is used internally.
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000201 To capture standard error in the result, use ``stderr=subprocess.STDOUT``::
Georg Brandlf9734072008-12-07 15:30:06 +0000202
203 >>> subprocess.check_output(
Mark Dickinson934896d2009-02-21 20:59:32 +0000204 ["/bin/sh", "-c", "ls non_existent_file ; exit 0"],
Georg Brandlf9734072008-12-07 15:30:06 +0000205 stderr=subprocess.STDOUT)
Mark Dickinson934896d2009-02-21 20:59:32 +0000206 'ls: non_existent_file: No such file or directory\n'
Georg Brandlf9734072008-12-07 15:30:06 +0000207
208 .. versionadded:: 3.1
209
210
Brett Cannona23810f2008-05-26 19:04:21 +0000211.. function:: getstatusoutput(cmd)
212 Return ``(status, output)`` of executing *cmd* in a shell.
213
214 Execute the string *cmd* in a shell with :func:`os.popen` and return a 2-tuple
215 ``(status, output)``. *cmd* is actually run as ``{ cmd ; } 2>&1``, so that the
216 returned output will contain output or error messages. A trailing newline is
217 stripped from the output. The exit status for the command can be interpreted
218 according to the rules for the C function :cfunc:`wait`. Example::
219
220 >>> import subprocess
221 >>> subprocess.getstatusoutput('ls /bin/ls')
222 (0, '/bin/ls')
223 >>> subprocess.getstatusoutput('cat /bin/junk')
224 (256, 'cat: /bin/junk: No such file or directory')
225 >>> subprocess.getstatusoutput('/bin/junk')
226 (256, 'sh: /bin/junk: not found')
227
Georg Brandl7d418902008-12-27 19:08:11 +0000228 Availability: UNIX.
229
Brett Cannona23810f2008-05-26 19:04:21 +0000230
231.. function:: getoutput(cmd)
Georg Brandlf9734072008-12-07 15:30:06 +0000232 Return output (stdout and stderr) of executing *cmd* in a shell.
Brett Cannona23810f2008-05-26 19:04:21 +0000233
234 Like :func:`getstatusoutput`, except the exit status is ignored and the return
235 value is a string containing the command's output. Example::
236
237 >>> import subprocess
238 >>> subprocess.getoutput('ls /bin/ls')
239 '/bin/ls'
240
Georg Brandl7d418902008-12-27 19:08:11 +0000241 Availability: UNIX.
242
Brett Cannona23810f2008-05-26 19:04:21 +0000243
Georg Brandl116aa622007-08-15 14:28:22 +0000244Exceptions
245^^^^^^^^^^
246
247Exceptions raised in the child process, before the new program has started to
248execute, will be re-raised in the parent. Additionally, the exception object
249will have one extra attribute called :attr:`child_traceback`, which is a string
250containing traceback information from the childs point of view.
251
252The most common exception raised is :exc:`OSError`. This occurs, for example,
253when trying to execute a non-existent file. Applications should prepare for
254:exc:`OSError` exceptions.
255
256A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid
257arguments.
258
259check_call() will raise :exc:`CalledProcessError`, if the called process returns
260a non-zero return code.
261
262
263Security
264^^^^^^^^
265
266Unlike some other popen functions, this implementation will never call /bin/sh
267implicitly. This means that all characters, including shell metacharacters, can
268safely be passed to child processes.
269
270
271Popen Objects
272-------------
273
274Instances of the :class:`Popen` class have the following methods:
275
276
277.. method:: Popen.poll()
278
Christian Heimes7f044312008-01-06 17:05:40 +0000279 Check if child process has terminated. Set and return :attr:`returncode`
280 attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000281
282
283.. method:: Popen.wait()
284
Christian Heimes7f044312008-01-06 17:05:40 +0000285 Wait for child process to terminate. Set and return :attr:`returncode`
286 attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000287
Georg Brandl734e2682008-08-12 08:18:18 +0000288 .. warning::
289
Philip Jenveyb0896842009-12-03 02:29:36 +0000290 This will deadlock when using ``stdout=PIPE`` and/or
291 ``stderr=PIPE`` and the child process generates enough output to
292 a pipe such that it blocks waiting for the OS pipe buffer to
293 accept more data. Use :meth:`communicate` to avoid that.
Georg Brandl734e2682008-08-12 08:18:18 +0000294
Georg Brandl116aa622007-08-15 14:28:22 +0000295
296.. method:: Popen.communicate(input=None)
297
298 Interact with process: Send data to stdin. Read data from stdout and stderr,
299 until end-of-file is reached. Wait for process to terminate. The optional
Georg Brandle11787a2008-07-01 19:10:52 +0000300 *input* argument should be a byte string to be sent to the child process, or
Georg Brandl116aa622007-08-15 14:28:22 +0000301 ``None``, if no data should be sent to the child.
302
Georg Brandlaf265f42008-12-07 15:06:20 +0000303 :meth:`communicate` returns a tuple ``(stdoutdata, stderrdata)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000304
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000305 Note that if you want to send data to the process's stdin, you need to create
306 the Popen object with ``stdin=PIPE``. Similarly, to get anything other than
307 ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or
308 ``stderr=PIPE`` too.
309
Christian Heimes7f044312008-01-06 17:05:40 +0000310 .. note::
Georg Brandl116aa622007-08-15 14:28:22 +0000311
Christian Heimes7f044312008-01-06 17:05:40 +0000312 The data read is buffered in memory, so do not use this method if the data
313 size is large or unlimited.
314
Georg Brandl116aa622007-08-15 14:28:22 +0000315
Christian Heimesa342c012008-04-20 21:01:16 +0000316.. method:: Popen.send_signal(signal)
317
318 Sends the signal *signal* to the child.
319
320 .. note::
321
322 On Windows only SIGTERM is supported so far. It's an alias for
323 :meth:`terminate`.
324
Christian Heimesa342c012008-04-20 21:01:16 +0000325
326.. method:: Popen.terminate()
327
328 Stop the child. On Posix OSs the method sends SIGTERM to the
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000329 child. On Windows the Win32 API function :cfunc:`TerminateProcess` is called
Christian Heimesa342c012008-04-20 21:01:16 +0000330 to stop the child.
331
Christian Heimesa342c012008-04-20 21:01:16 +0000332
333.. method:: Popen.kill()
334
335 Kills the child. On Posix OSs the function sends SIGKILL to the child.
336 On Windows :meth:`kill` is an alias for :meth:`terminate`.
337
Christian Heimesa342c012008-04-20 21:01:16 +0000338
Georg Brandl116aa622007-08-15 14:28:22 +0000339The following attributes are also available:
340
Georg Brandl734e2682008-08-12 08:18:18 +0000341.. warning::
342
Georg Brandle720c0a2009-04-27 16:20:50 +0000343 Use :meth:`communicate` rather than :attr:`.stdin.write <stdin>`,
344 :attr:`.stdout.read <stdout>` or :attr:`.stderr.read <stderr>` to avoid
345 deadlocks due to any of the other OS pipe buffers filling up and blocking the
346 child process.
Georg Brandl734e2682008-08-12 08:18:18 +0000347
348
Georg Brandl116aa622007-08-15 14:28:22 +0000349.. attribute:: Popen.stdin
350
Georg Brandlaf265f42008-12-07 15:06:20 +0000351 If the *stdin* argument was :data:`PIPE`, this attribute is a file object
352 that provides input to the child process. Otherwise, it is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000353
354
355.. attribute:: Popen.stdout
356
Georg Brandlaf265f42008-12-07 15:06:20 +0000357 If the *stdout* argument was :data:`PIPE`, this attribute is a file object
358 that provides output from the child process. Otherwise, it is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000359
360
361.. attribute:: Popen.stderr
362
Georg Brandlaf265f42008-12-07 15:06:20 +0000363 If the *stderr* argument was :data:`PIPE`, this attribute is a file object
364 that provides error output from the child process. Otherwise, it is
365 ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000366
367
368.. attribute:: Popen.pid
369
370 The process ID of the child process.
371
372
373.. attribute:: Popen.returncode
374
Christian Heimes7f044312008-01-06 17:05:40 +0000375 The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly
376 by :meth:`communicate`). A ``None`` value indicates that the process
377 hasn't terminated yet.
Georg Brandl48310cd2009-01-03 21:18:54 +0000378
Christian Heimes7f044312008-01-06 17:05:40 +0000379 A negative value ``-N`` indicates that the child was terminated by signal
380 ``N`` (Unix only).
Georg Brandl116aa622007-08-15 14:28:22 +0000381
382
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000383.. _subprocess-replacements:
384
Georg Brandl116aa622007-08-15 14:28:22 +0000385Replacing Older Functions with the subprocess Module
386----------------------------------------------------
387
388In this section, "a ==> b" means that b can be used as a replacement for a.
389
390.. note::
391
392 All functions in this section fail (more or less) silently if the executed
393 program cannot be found; this module raises an :exc:`OSError` exception.
394
395In the following examples, we assume that the subprocess module is imported with
396"from subprocess import \*".
397
398
399Replacing /bin/sh shell backquote
400^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
401
402::
403
404 output=`mycmd myarg`
405 ==>
406 output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
407
408
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000409Replacing shell pipeline
410^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000411
412::
413
414 output=`dmesg | grep hda`
415 ==>
416 p1 = Popen(["dmesg"], stdout=PIPE)
417 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
418 output = p2.communicate()[0]
419
420
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000421Replacing :func:`os.system`
422^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000423
424::
425
426 sts = os.system("mycmd" + " myarg")
427 ==>
428 p = Popen("mycmd" + " myarg", shell=True)
Alexandre Vassalottie52e3782009-07-17 09:18:18 +0000429 sts = os.waitpid(p.pid, 0)[1]
Georg Brandl116aa622007-08-15 14:28:22 +0000430
431Notes:
432
433* Calling the program through the shell is usually not required.
434
435* It's easier to look at the :attr:`returncode` attribute than the exit status.
436
437A more realistic example would look like this::
438
439 try:
440 retcode = call("mycmd" + " myarg", shell=True)
441 if retcode < 0:
Collin Winterc79461b2007-09-01 23:34:30 +0000442 print("Child was terminated by signal", -retcode, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000443 else:
Collin Winterc79461b2007-09-01 23:34:30 +0000444 print("Child returned", retcode, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000445 except OSError as e:
Collin Winterc79461b2007-09-01 23:34:30 +0000446 print("Execution failed:", e, file=sys.stderr)
Georg Brandl116aa622007-08-15 14:28:22 +0000447
448
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000449Replacing the :func:`os.spawn <os.spawnl>` family
450^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000451
452P_NOWAIT example::
453
454 pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
455 ==>
456 pid = Popen(["/bin/mycmd", "myarg"]).pid
457
458P_WAIT example::
459
460 retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
461 ==>
462 retcode = call(["/bin/mycmd", "myarg"])
463
464Vector example::
465
466 os.spawnvp(os.P_NOWAIT, path, args)
467 ==>
468 Popen([path] + args[1:])
469
470Environment example::
471
472 os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
473 ==>
474 Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
475
476
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000477
478Replacing :func:`os.popen`, :func:`os.popen2`, :func:`os.popen3`
479^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000480
481::
482
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000483 (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
Georg Brandl116aa622007-08-15 14:28:22 +0000484 ==>
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000485 p = Popen(cmd, shell=True, bufsize=bufsize,
486 stdin=PIPE, stdout=PIPE, close_fds=True)
487 (child_stdin, child_stdout) = (p.stdin, p.stdout)
Georg Brandl116aa622007-08-15 14:28:22 +0000488
489::
490
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000491 (child_stdin,
492 child_stdout,
493 child_stderr) = os.popen3(cmd, mode, bufsize)
Georg Brandl116aa622007-08-15 14:28:22 +0000494 ==>
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000495 p = Popen(cmd, shell=True, bufsize=bufsize,
496 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
497 (child_stdin,
498 child_stdout,
499 child_stderr) = (p.stdin, p.stdout, p.stderr)
500
501::
502
503 (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
504 ==>
505 p = Popen(cmd, shell=True, bufsize=bufsize,
506 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
507 (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
508
509Return code handling translates as follows::
510
511 pipe = os.popen(cmd, 'w')
512 ...
513 rc = pipe.close()
514 if rc != None and rc % 256:
Ezio Melotti985e24d2009-09-13 07:54:02 +0000515 print("There were some errors")
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000516 ==>
517 process = Popen(cmd, 'w', stdin=PIPE)
518 ...
519 process.stdin.close()
520 if process.wait() != 0:
Ezio Melotti985e24d2009-09-13 07:54:02 +0000521 print("There were some errors")
Benjamin Peterson87c8d872009-06-11 22:54:11 +0000522
523
524Replacing functions from the :mod:`popen2` module
525^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
526
527.. note::
528
529 If the cmd argument to popen2 functions is a string, the command is executed
530 through /bin/sh. If it is a list, the command is directly executed.
531
532::
533
534 (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
535 ==>
536 p = Popen(["somestring"], shell=True, bufsize=bufsize,
537 stdin=PIPE, stdout=PIPE, close_fds=True)
538 (child_stdout, child_stdin) = (p.stdout, p.stdin)
539
540::
541
542 (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
543 ==>
544 p = Popen(["mycmd", "myarg"], bufsize=bufsize,
545 stdin=PIPE, stdout=PIPE, close_fds=True)
546 (child_stdout, child_stdin) = (p.stdout, p.stdin)
547
548:class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as
549:class:`subprocess.Popen`, except that:
550
551* :class:`Popen` raises an exception if the execution fails.
552
553* the *capturestderr* argument is replaced with the *stderr* argument.
554
555* ``stdin=PIPE`` and ``stdout=PIPE`` must be specified.
556
557* popen2 closes all file descriptors by default, but you have to specify
558 ``close_fds=True`` with :class:`Popen`.