rest25/library/subprocess.rst => rest262/library/subprocess.rst
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
n15-replace several other, older modules and functions, such as:
n15+replace several other, older modules and functions, such as::
16- 
17-.. % XXX Should add pointers to this module to at least the popen2
18-.. % and commands sections.
19- 
20-::
21
22   os.system
23   os.spawn*
24   os.popen*
25   popen2.*
26   commands.*
27
28Information about how the :mod:`subprocess` module can be used to replace these
29modules and functions can be found in the following sections.
30
n26+.. seealso::
27+ 
28+   :pep:`324` -- PEP proposing the subprocess module
29+ 
31
32Using the subprocess Module
33---------------------------
34
35This module defines one class called :class:`Popen`:
36
37
38.. 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)
39
40   Arguments are:
41
n42-   *args* should be a string, or a sequence of program arguments.  The program to
n41+   *args* should be a string, or a sequence of program arguments.  The program
43-   execute is normally the first item in the args sequence or string, but can be
42+   to execute is normally the first item in the args sequence or the string if a
44-   explicitly set by using the executable argument.
43+   string is given, but can be explicitly set by using the *executable*
44+   argument.
45
46   On Unix, with *shell=False* (default): In this case, the Popen class uses
47   :meth:`os.execvp` to execute the child program. *args* should normally be a
48   sequence.  A string will be treated as a sequence with the string as the only
49   item (the program to execute).
50
51   On Unix, with *shell=True*: If args is a string, it specifies the command string
52   to execute through the shell.  If *args* is a sequence, the first item specifies
68
69   The *executable* argument specifies the program to execute. It is very seldom
70   needed: Usually, the program to execute is defined by the *args* argument. If
71   ``shell=True``, the *executable* argument specifies which shell to use. On Unix,
72   the default shell is :file:`/bin/sh`.  On Windows, the default shell is
73   specified by the :envvar:`COMSPEC` environment variable.
74
75   *stdin*, *stdout* and *stderr* specify the executed programs' standard input,
n76-   standard output and standard error file handles, respectively.  Valid values are
n76+   standard output and standard error file handles, respectively.  Valid values
77-   ``PIPE``, an existing file descriptor (a positive integer), an existing file
77+   are :data:`PIPE`, an existing file descriptor (a positive integer), an
78-   object, and ``None``.  ``PIPE`` indicates that a new pipe to the child should be
78+   existing file object, and ``None``.  :data:`PIPE` indicates that a new pipe
79-   created.  With ``None``, no redirection will occur; the child's file handles
79+   to the child should be created.  With ``None``, no redirection will occur;
80-   will be inherited from the parent.  Additionally, *stderr* can be ``STDOUT``,
80+   the child's file handles will be inherited from the parent.  Additionally,
81-   which indicates that the stderr data from the applications should be captured
81+   *stderr* can be :data:`STDOUT`, which indicates that the stderr data from the
82-   into the same file handle as for stdout.
82+   applications should be captured into the same file handle as for stdout.
83
84   If *preexec_fn* is set to a callable object, this object will be called in the
85   child process just before the child is executed. (Unix only)
86
87   If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and
n88-   :const:`2` will be closed before the child process is executed. (Unix only)
n88+   :const:`2` will be closed before the child process is executed. (Unix only).
89+   Or, on Windows, if *close_fds* is true then no handles will be inherited by the
90+   child process.  Note that on Windows, you cannot set *close_fds* to true and
91+   also redirect the standard handles by setting *stdin*, *stdout* or *stderr*.
89
90   If *shell* is :const:`True`, the specified command will be executed through the
91   shell.
92
93   If *cwd* is not ``None``, the child's current directory will be changed to *cwd*
94   before it is executed.  Note that this directory is not considered when
95   searching the executable, so you can't specify the program's path relative to
96   *cwd*.
97
n98-   If *env* is not ``None``, it defines the environment variables for the new
n101+   If *env* is not ``None``, it must be a mapping that defines the environment
99-   process.
102+   variables for the new process; these are used instead of inheriting the current
103+   process' environment, which is the default behavior.
100
101   If *universal_newlines* is :const:`True`, the file objects stdout and stderr are
102   opened as text files, but lines may be terminated by any of ``'\n'``, the Unix
n103-   end-of-line convention, ``'\r'``, the Macintosh convention or ``'\r\n'``, the
n107+   end-of-line convention, ``'\r'``, the old Macintosh convention or ``'\r\n'``, the
104   Windows convention. All of these external representations are seen as ``'\n'``
105   by the Python program.
106
107   .. note::
108
109      This feature is only available if Python is built with universal newline support
110      (the default).  Also, the newlines attribute of the file objects :attr:`stdout`,
111      :attr:`stdin` and :attr:`stderr` are not updated by the communicate() method.
112
113   The *startupinfo* and *creationflags*, if given, will be passed to the
114   underlying CreateProcess() function.  They can specify things such as appearance
115   of the main window and priority for the new process.  (Windows only)
116
117
n122+.. data:: PIPE
123+ 
124+   Special value that can be used as the *stdin*, *stdout* or *stderr* argument
125+   to :class:`Popen` and indicates that a pipe to the standard stream should be
126+   opened.
127+ 
128+ 
129+.. data:: STDOUT
130+ 
131+   Special value that can be used as the *stderr* argument to :class:`Popen` and
132+   indicates that standard error should go into the same handle as standard
133+   output.
134+ 
135+ 
118Convenience Functions
119^^^^^^^^^^^^^^^^^^^^^
120
121This module also defines two shortcut functions:
122
123
124.. function:: call(*popenargs, **kwargs)
125
129   The arguments are the same as for the Popen constructor.  Example::
130
131      retcode = call(["ls", "-l"])
132
133
134.. function:: check_call(*popenargs, **kwargs)
135
136   Run command with arguments.  Wait for command to complete. If the exit code was
n137-   zero then return, otherwise raise :exc:`CalledProcessError.` The
n155+   zero then return, otherwise raise :exc:`CalledProcessError`. The
138   :exc:`CalledProcessError` object will have the return code in the
139   :attr:`returncode` attribute.
140
141   The arguments are the same as for the Popen constructor.  Example::
142
143      check_call(["ls", "-l"])
n162+ 
163+   .. versionadded:: 2.5
144
145
146Exceptions
147^^^^^^^^^^
148
149Exceptions raised in the child process, before the new program has started to
150execute, will be re-raised in the parent.  Additionally, the exception object
151will have one extra attribute called :attr:`child_traceback`, which is a string
171
172
173Popen Objects
174-------------
175
176Instances of the :class:`Popen` class have the following methods:
177
178
n179-.. method:: XXX Class.poll()
n199+.. method:: Popen.poll()
180
n181-   Check if child process has terminated.  Returnreturncode attribute.
n201+   Check if child process has terminated.  Set and return :attr:`returncode`
202+   attribute.
182
183
n184-.. method:: XXX Class.wait()
n205+.. method:: Popen.wait()
185
n186-   Wait for child process to terminate.  Returnreturncode attribute.
n207+   Wait for child process to terminate.  Set and return :attr:`returncode`
208+   attribute.
187
n210+   .. warning::
188
n212+      This will deadlock if the child process generates enough output to a
213+      stdout or stderr pipe such that it blocks waiting for the OS pipe buffer
214+      to accept more data.  Use :meth:`communicate` to avoid that.
215+ 
216+ 
189-.. method:: XXX Class.communicate(input=None)
217+.. method:: Popen.communicate(input=None)
190
191   Interact with process: Send data to stdin.  Read data from stdout and stderr,
192   until end-of-file is reached.  Wait for process to terminate. The optional
193   *input* argument should be a string to be sent to the child process, or
194   ``None``, if no data should be sent to the child.
195
n196-   communicate() returns a tuple (stdout, stderr).
n224+   :meth:`communicate` returns a tuple ``(stdoutdata, stderrdata)``.
225+ 
226+   Note that if you want to send data to the process's stdin, you need to create
227+   the Popen object with ``stdin=PIPE``.  Similarly, to get anything other than
228+   ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or
229+   ``stderr=PIPE`` too.
197
198   .. note::
199
n200-      The data read is buffered in memory, so do not use this method if the data size
n233+      The data read is buffered in memory, so do not use this method if the data
201-      is large or unlimited.
234+      size is large or unlimited.
235+ 
236+ 
237+.. method:: Popen.send_signal(signal)
238+ 
239+   Sends the signal *signal* to the child.
240+ 
241+   .. note::
242+ 
243+      On Windows only SIGTERM is supported so far. It's an alias for
244+      :meth:`terminate`.
245+ 
246+   .. versionadded:: 2.6
247+ 
248+ 
249+.. method:: Popen.terminate()
250+ 
251+   Stop the child. On Posix OSs the method sends SIGTERM to the
252+   child. On Windows the Win32 API function :cfunc:`TerminateProcess` is called
253+   to stop the child.
254+ 
255+   .. versionadded:: 2.6
256+ 
257+ 
258+.. method:: Popen.kill()
259+ 
260+   Kills the child. On Posix OSs the function sends SIGKILL to the child.
261+   On Windows :meth:`kill` is an alias for :meth:`terminate`.
262+ 
263+   .. versionadded:: 2.6
264+ 
202
203The following attributes are also available:
204
n268+.. warning::
205
n270+   Use :meth:`communicate` rather than :meth:`.stdin.write`,
271+   :meth:`.stdout.read` or :meth:`.stderr.read` to avoid deadlocks due
272+   to any of the other OS pipe buffers filling up and blocking the child
273+   process.
274+ 
275+ 
206-.. attribute:: XXX Class.stdin
276+.. attribute:: Popen.stdin
207
n208-   If the *stdin* argument i``PIPE``, this attribute is a file object that
n278+   If the *stdin* argument wa:data:`PIPE`, this attribute is a file object
209-   provides input to the child process.  Otherwise, it is ``None``.
279+   that provides input to the child process.  Otherwise, it is ``None``.
210
211
n212-.. attribute:: XXX Class.stdout
n282+.. attribute:: Popen.stdout
213
n214-   If the *stdout* argument i``PIPE``, this attribute is a file object that
n284+   If the *stdout* argument wa:data:`PIPE`, this attribute is a file object
215-   provides output from the child process.  Otherwise, it is ``None``.
285+   that provides output from the child process.  Otherwise, it is ``None``.
216
217
n218-.. attribute:: XXX Class.stderr
n288+.. attribute:: Popen.stderr
219
n220-   If the *stderr* argument i``PIPE``, this attribute is file object that
n290+   If the *stderr* argument wa:data:`PIPE`, this attribute is a file object
221-   provides error output from the child process.  Otherwise, it is ``None``.
291+   that provides error output from the child process.  Otherwise, it is
292+   ``None``.
222
223
n224-.. attribute:: XXX Class.pid
n295+.. attribute:: Popen.pid
225
226   The process ID of the child process.
227
228
n229-.. attribute:: XXX Class.returncode
n300+.. attribute:: Popen.returncode
230
n231-   The child return code.  A ``None`` value indicates that the process hasn't
n302+   The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly
232-   terminated yet.  A negative value -N indicates that the child was terminated by
303+   by :meth:`communicate`).  A ``None`` value indicates that the process
304+   hasn't terminated yet.
305+ 
306+   A negative value ``-N`` indicates that the child was terminated by signal
233-   signal N (Unix only).
307+   ``N`` (Unix only).
234
n309+ 
310+.. _subprocess-replacements:
235
236Replacing Older Functions with the subprocess Module
237----------------------------------------------------
238
239In this section, "a ==> b" means that b can be used as a replacement for a.
240
241.. note::
242
252
253::
254
255   output=`mycmd myarg`
256   ==>
257   output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
258
259
n260-Replacing shell pipe line
n336+Replacing shell pipeline
261-^^^^^^^^^^^^^^^^^^^^^^^^^
337+^^^^^^^^^^^^^^^^^^^^^^^^
262
263::
264
265   output=`dmesg | grep hda`
266   ==>
267   p1 = Popen(["dmesg"], stdout=PIPE)
268   p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
269   output = p2.communicate()[0]
292       if retcode < 0:
293           print >>sys.stderr, "Child was terminated by signal", -retcode
294       else:
295           print >>sys.stderr, "Child returned", retcode
296   except OSError, e:
297       print >>sys.stderr, "Execution failed:", e
298
299
n300-Replacing os.spawn\*
n376+Replacing the os.spawn family
301-^^^^^^^^^^^^^^^^^^^^
377+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
302
303P_NOWAIT example::
304
305   pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
306   ==>
307   pid = Popen(["/bin/mycmd", "myarg"]).pid
308
309P_WAIT example::
320
321Environment example::
322
323   os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
324   ==>
325   Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
326
327
n328-Replacing os.popen\*
n404+Replacing os.popen, os.popen2, os.popen3
329-^^^^^^^^^^^^^^^^^^^^
405+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
330
331::
332
n333-   pipe = os.popen(cmd, mode='r', bufsize)
n409+   pipe = os.popen(cmd, 'r', bufsize)
334   ==>
335   pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
336
337::
338
n339-   pipe = os.popen(cmd, mode='w', bufsize)
n415+   pipe = os.popen(cmd, 'w', bufsize)
340   ==>
341   pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
342
343::
344
345   (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
346   ==>
347   p = Popen(cmd, shell=True, bufsize=bufsize,
364
365   (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
366   ==>
367   p = Popen(cmd, shell=True, bufsize=bufsize,
368             stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
369   (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
370
371
n372-Replacing popen2.\*
n448+Replacing functions from the popen2 module
373-^^^^^^^^^^^^^^^^^^^
449+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
374
375.. note::
376
377   If the cmd argument to popen2 functions is a string, the command is executed
378   through /bin/sh.  If it is a list, the command is directly executed.
379
380::
381
388::
389
390   (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
391   ==>
392   p = Popen(["mycmd", "myarg"], bufsize=bufsize,
393             stdin=PIPE, stdout=PIPE, close_fds=True)
394   (child_stdout, child_stdin) = (p.stdout, p.stdin)
395
n396-The popen2.Popen3 and popen2.Popen4 basically works as subprocess.Popen, except
n472+:class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as
397-that:
473+:class:`subprocess.Popen`, except that:
398
n399-subprocess.Popen raises an exception if the execution fails
n475+:class:`Popen` raises an exception if the execution fails.
400
401* the *capturestderr* argument is replaced with the *stderr* argument.
402
n403-* stdin=PIPE and stdout=PIPE must be specified.
n479+``stdin=PIPE`` and ``stdout=PIPE`` must be specified.
404
405* popen2 closes all file descriptors by default, but you have to specify
t406-  close_fds=True with subprocess.Popen.
t482+  ``close_fds=True`` with :class:`Popen`.
407
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op