blob: bde92eb0cc1c4ce4fcb487e58ff0821fe7529131 [file] [log] [blame]
Fredrik Lundhb04b6af2004-10-17 16:29:48 +00001\section{\module{subprocess} --- Subprocess management}
2
3\declaremodule{standard}{subprocess}
4\modulesynopsis{Subprocess management.}
5\moduleauthor{Peter \AA strand}{astrand@lysator.liu.se}
6\sectionauthor{Peter \AA strand}{astrand@lysator.liu.se}
7
8\versionadded{2.4}
9
10The \module{subprocess} module allows you to spawn new processes,
11connect to their input/output/error pipes, and obtain their return
12codes. This module intends to replace several other, older modules
13and functions, such as:
14
15% XXX Should add pointers to this module to at least the popen2
16% and commands sections.
17
18\begin{verbatim}
19os.system
20os.spawn*
21os.popen*
22popen2.*
23commands.*
24\end{verbatim}
25
26Information about how the \module{subprocess} module can be used to
27replace these modules and functions can be found in the following
28sections.
29
30\subsection{Using the subprocess Module}
31
32This module defines one class called \class{Popen}:
33
34\begin{classdesc}{Popen}{args, bufsize=0, executable=None,
35 stdin=None, stdout=None, stderr=None,
36 preexec_fn=None, close_fds=False, shell=False,
37 cwd=None, env=None, universal_newlines=False,
38 startupinfo=None, creationflags=0}
39
40Arguments are:
41
42\var{args} should be a string, or a sequence of program arguments. The
43program to execute is normally the first item in the args sequence or
44string, but can be explicitly set by using the executable argument.
45
46On \UNIX{}, with \var{shell=False} (default): In this case, the Popen
47class uses \method{os.execvp()} to execute the child program.
48\var{args} should normally be a sequence. A string will be treated as a
49sequence with the string as the only item (the program to execute).
50
51On \UNIX{}, with \var{shell=True}: If args is a string, it specifies the
52command string to execute through the shell. If \var{args} is a
53sequence, the first item specifies the command string, and any
54additional items will be treated as additional shell arguments.
55
56On Windows: the \class{Popen} class uses CreateProcess() to execute
57the child program, which operates on strings. If \var{args} is a
58sequence, it will be converted to a string using the
59\method{list2cmdline} method. Please note that not all MS Windows
60applications interpret the command line the same way:
61\method{list2cmdline} is designed for applications using the same
62rules as the MS C runtime.
63
64\var{bufsize}, if given, has the same meaning as the corresponding
65argument to the built-in open() function: \constant{0} means unbuffered,
66\constant{1} means line buffered, any other positive value means use a
67buffer of (approximately) that size. A negative \var{bufsize} means to
68use the system default, which usually means fully buffered. The default
69value for \var{bufsize} is \constant{0} (unbuffered).
70
Peter Astrand35461882004-11-07 16:38:08 +000071The \var{executable} argument specifies the program to execute. It is
72very seldom needed: Usually, the program to execute is defined by the
Thomas Wouters477c8d52006-05-27 19:21:47 +000073\var{args} argument. If \code{shell=True}, the \var{executable}
Peter Astrand35461882004-11-07 16:38:08 +000074argument specifies which shell to use. On \UNIX{}, the default shell
Thomas Wouters477c8d52006-05-27 19:21:47 +000075is \file{/bin/sh}. On Windows, the default shell is specified by the
76\envvar{COMSPEC} environment variable.
Peter Astrand35461882004-11-07 16:38:08 +000077
Fredrik Lundhb04b6af2004-10-17 16:29:48 +000078\var{stdin}, \var{stdout} and \var{stderr} specify the executed
79programs' standard input, standard output and standard error file
80handles, respectively. Valid values are \code{PIPE}, an existing file
81descriptor (a positive integer), an existing file object, and
82\code{None}. \code{PIPE} indicates that a new pipe to the child
83should be created. With \code{None}, no redirection will occur; the
84child's file handles will be inherited from the parent. Additionally,
85\var{stderr} can be \code{STDOUT}, which indicates that the stderr
86data from the applications should be captured into the same file
87handle as for stdout.
88
89If \var{preexec_fn} is set to a callable object, this object will be
90called in the child process just before the child is executed.
Thomas Wouters477c8d52006-05-27 19:21:47 +000091(\UNIX{} only)
Fredrik Lundhb04b6af2004-10-17 16:29:48 +000092
93If \var{close_fds} is true, all file descriptors except \constant{0},
94\constant{1} and \constant{2} will be closed before the child process is
Thomas Wouters477c8d52006-05-27 19:21:47 +000095executed. (\UNIX{} only)
Fredrik Lundhb04b6af2004-10-17 16:29:48 +000096
97If \var{shell} is \constant{True}, the specified command will be
98executed through the shell.
99
Thomas Wouters477c8d52006-05-27 19:21:47 +0000100If \var{cwd} is not \code{None}, the child's current directory will be
101changed to \var{cwd} before it is executed. Note that this directory
102is not considered when searching the executable, so you can't specify
103the program's path relative to \var{cwd}.
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000104
105If \var{env} is not \code{None}, it defines the environment variables
106for the new process.
107
108If \var{universal_newlines} is \constant{True}, the file objects stdout
Georg Brandl0f194232006-01-01 21:35:20 +0000109and stderr are opened as text files, but lines may be terminated by
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000110any of \code{'\e n'}, the Unix end-of-line convention, \code{'\e r'},
111the Macintosh convention or \code{'\e r\e n'}, the Windows convention.
112All of these external representations are seen as \code{'\e n'} by the
113Python program. \note{This feature is only available if Python is built
114with universal newline support (the default). Also, the newlines
115attribute of the file objects \member{stdout}, \member{stdin} and
116\member{stderr} are not updated by the communicate() method.}
117
118The \var{startupinfo} and \var{creationflags}, if given, will be
119passed to the underlying CreateProcess() function. They can specify
120things such as appearance of the main window and priority for the new
121process. (Windows only)
122\end{classdesc}
123
124\subsubsection{Convenience Functions}
125
Peter Astrand454f7672005-01-01 09:36:35 +0000126This module also defines two shortcut functions:
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000127
Peter Astrand5f5e1412004-12-05 20:15:36 +0000128\begin{funcdesc}{call}{*popenargs, **kwargs}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000129Run command with arguments. Wait for command to complete, then
130return the \member{returncode} attribute.
131
132The arguments are the same as for the Popen constructor. Example:
133
134\begin{verbatim}
135 retcode = call(["ls", "-l"])
136\end{verbatim}
137\end{funcdesc}
138
Peter Astrand454f7672005-01-01 09:36:35 +0000139\begin{funcdesc}{check_call}{*popenargs, **kwargs}
140Run command with arguments. Wait for command to complete. If the exit
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000141code was zero then return, otherwise raise \exception{CalledProcessError.}
142The \exception{CalledProcessError} object will have the return code in the
Peter Astrand454f7672005-01-01 09:36:35 +0000143\member{errno} attribute.
144
145The arguments are the same as for the Popen constructor. Example:
146
147\begin{verbatim}
148 check_call(["ls", "-l"])
149\end{verbatim}
150\end{funcdesc}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000151
152\subsubsection{Exceptions}
153
154Exceptions raised in the child process, before the new program has
155started to execute, will be re-raised in the parent. Additionally,
156the exception object will have one extra attribute called
157\member{child_traceback}, which is a string containing traceback
158information from the childs point of view.
159
160The most common exception raised is \exception{OSError}. This occurs,
161for example, when trying to execute a non-existent file. Applications
162should prepare for \exception{OSError} exceptions.
163
164A \exception{ValueError} will be raised if \class{Popen} is called
165with invalid arguments.
166
Peter Astrand454f7672005-01-01 09:36:35 +0000167check_call() will raise \exception{CalledProcessError}, which is a
168subclass of \exception{OSError}, if the called process returns a
169non-zero return code.
170
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000171
172\subsubsection{Security}
173
174Unlike some other popen functions, this implementation will never call
175/bin/sh implicitly. This means that all characters, including shell
176metacharacters, can safely be passed to child processes.
177
178
179\subsection{Popen Objects}
180
181Instances of the \class{Popen} class have the following methods:
182
183\begin{methoddesc}{poll}{}
184Check if child process has terminated. Returns returncode
185attribute.
186\end{methoddesc}
187
188\begin{methoddesc}{wait}{}
189Wait for child process to terminate. Returns returncode attribute.
190\end{methoddesc}
191
192\begin{methoddesc}{communicate}{input=None}
193Interact with process: Send data to stdin. Read data from stdout and
194stderr, until end-of-file is reached. Wait for process to terminate.
Walter Dörwald769f8212005-04-14 20:08:59 +0000195The optional \var{input} argument should be a string to be sent to the
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000196child process, or \code{None}, if no data should be sent to the child.
197
198communicate() returns a tuple (stdout, stderr).
199
200\note{The data read is buffered in memory, so do not use this method
201if the data size is large or unlimited.}
202\end{methoddesc}
203
204The following attributes are also available:
205
206\begin{memberdesc}{stdin}
207If the \var{stdin} argument is \code{PIPE}, this attribute is a file
208object that provides input to the child process. Otherwise, it is
209\code{None}.
210\end{memberdesc}
211
212\begin{memberdesc}{stdout}
213If the \var{stdout} argument is \code{PIPE}, this attribute is a file
214object that provides output from the child process. Otherwise, it is
215\code{None}.
216\end{memberdesc}
217
218\begin{memberdesc}{stderr}
219If the \var{stderr} argument is \code{PIPE}, this attribute is file
220object that provides error output from the child process. Otherwise,
221it is \code{None}.
222\end{memberdesc}
223
224\begin{memberdesc}{pid}
225The process ID of the child process.
226\end{memberdesc}
227
228\begin{memberdesc}{returncode}
229The child return code. A \code{None} value indicates that the process
230hasn't terminated yet. A negative value -N indicates that the child
231was terminated by signal N (\UNIX{} only).
232\end{memberdesc}
233
234
235\subsection{Replacing Older Functions with the subprocess Module}
236
237In this section, "a ==> b" means that b can be used as a replacement
238for a.
239
240\note{All functions in this section fail (more or less) silently if
241the executed program cannot be found; this module raises an
242\exception{OSError} exception.}
243
244In the following examples, we assume that the subprocess module is
245imported with "from subprocess import *".
246
247\subsubsection{Replacing /bin/sh shell backquote}
248
249\begin{verbatim}
250output=`mycmd myarg`
251==>
252output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
253\end{verbatim}
254
255\subsubsection{Replacing shell pipe line}
256
257\begin{verbatim}
258output=`dmesg | grep hda`
259==>
260p1 = Popen(["dmesg"], stdout=PIPE)
Peter Astrand6fdf3cb2004-11-30 18:06:42 +0000261p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000262output = p2.communicate()[0]
263\end{verbatim}
264
265\subsubsection{Replacing os.system()}
266
267\begin{verbatim}
268sts = os.system("mycmd" + " myarg")
269==>
270p = Popen("mycmd" + " myarg", shell=True)
271sts = os.waitpid(p.pid, 0)
272\end{verbatim}
273
274Notes:
275
276\begin{itemize}
277\item Calling the program through the shell is usually not required.
278\item It's easier to look at the \member{returncode} attribute than
279 the exit status.
280\end{itemize}
281
282A more realistic example would look like this:
283
284\begin{verbatim}
285try:
286 retcode = call("mycmd" + " myarg", shell=True)
287 if retcode < 0:
288 print >>sys.stderr, "Child was terminated by signal", -retcode
289 else:
290 print >>sys.stderr, "Child returned", retcode
291except OSError, e:
292 print >>sys.stderr, "Execution failed:", e
293\end{verbatim}
294
295\subsubsection{Replacing os.spawn*}
296
297P_NOWAIT example:
298
299\begin{verbatim}
300pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
301==>
302pid = Popen(["/bin/mycmd", "myarg"]).pid
303\end{verbatim}
304
305P_WAIT example:
306
307\begin{verbatim}
308retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
309==>
310retcode = call(["/bin/mycmd", "myarg"])
311\end{verbatim}
312
313Vector example:
314
315\begin{verbatim}
316os.spawnvp(os.P_NOWAIT, path, args)
317==>
318Popen([path] + args[1:])
319\end{verbatim}
320
321Environment example:
322
323\begin{verbatim}
324os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
325==>
326Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
327\end{verbatim}
328
329\subsubsection{Replacing os.popen*}
330
331\begin{verbatim}
332pipe = os.popen(cmd, mode='r', bufsize)
333==>
334pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
335\end{verbatim}
336
337\begin{verbatim}
338pipe = os.popen(cmd, mode='w', bufsize)
339==>
340pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
341\end{verbatim}
342
343\begin{verbatim}
344(child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
345==>
346p = Popen(cmd, shell=True, bufsize=bufsize,
347 stdin=PIPE, stdout=PIPE, close_fds=True)
348(child_stdin, child_stdout) = (p.stdin, p.stdout)
349\end{verbatim}
350
351\begin{verbatim}
352(child_stdin,
353 child_stdout,
354 child_stderr) = os.popen3(cmd, mode, bufsize)
355==>
356p = Popen(cmd, shell=True, bufsize=bufsize,
357 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
358(child_stdin,
359 child_stdout,
360 child_stderr) = (p.stdin, p.stdout, p.stderr)
361\end{verbatim}
362
363\begin{verbatim}
364(child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
365==>
366p = Popen(cmd, shell=True, bufsize=bufsize,
367 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
368(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
369\end{verbatim}
370
371\subsubsection{Replacing popen2.*}
372
373\note{If the cmd argument to popen2 functions is a string, the command
374is executed through /bin/sh. If it is a list, the command is directly
375executed.}
376
377\begin{verbatim}
378(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
379==>
Walter Dörwald769f8212005-04-14 20:08:59 +0000380p = Popen(["somestring"], shell=True, bufsize=bufsize,
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000381 stdin=PIPE, stdout=PIPE, close_fds=True)
382(child_stdout, child_stdin) = (p.stdout, p.stdin)
383\end{verbatim}
384
385\begin{verbatim}
386(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
387==>
388p = Popen(["mycmd", "myarg"], bufsize=bufsize,
389 stdin=PIPE, stdout=PIPE, close_fds=True)
390(child_stdout, child_stdin) = (p.stdout, p.stdin)
391\end{verbatim}
392
Neal Norwitzb7b54f72006-02-04 23:00:48 +0000393The popen2.Popen3 and popen2.Popen4 basically works as subprocess.Popen,
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000394except that:
395
396\begin{itemize}
397\item subprocess.Popen raises an exception if the execution fails
398
399\item the \var{capturestderr} argument is replaced with the \var{stderr}
400 argument.
401
402\item stdin=PIPE and stdout=PIPE must be specified.
403
404\item popen2 closes all file descriptors by default, but you have to
405 specify close_fds=True with subprocess.Popen.
406\end{itemize}