blob: 03072f7258a7d6e41f6a4a00637022c9f232b0f1 [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
Georg Brandlb1582552006-05-10 16:09:03 +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
Georg Brandlb1582552006-05-10 16:09:03 +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.
Georg Brandlb1582552006-05-10 16:09:03 +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
Georg Brandlb1582552006-05-10 16:09:03 +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
Georg Brandlb1582552006-05-10 16:09:03 +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
Fred Drakee0d4aec2006-07-30 03:03:43 +0000110any of \code{'\e n'}, the \UNIX{} end-of-line convention, \code{'\e r'},
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000111the 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
Georg Brandldb815ab2006-03-17 16:26:31 +0000141code was zero then return, otherwise raise \exception{CalledProcessError.}
142The \exception{CalledProcessError} object will have the return code in the
Peter Astrand7d1d4362006-07-14 14:04:45 +0000143\member{returncode} attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000144
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 Astrand7d1d4362006-07-14 14:04:45 +0000167check_call() will raise \exception{CalledProcessError}, if the called
168process returns a non-zero return code.
Peter Astrand454f7672005-01-01 09:36:35 +0000169
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000170
171\subsubsection{Security}
172
173Unlike some other popen functions, this implementation will never call
174/bin/sh implicitly. This means that all characters, including shell
175metacharacters, can safely be passed to child processes.
176
177
178\subsection{Popen Objects}
179
180Instances of the \class{Popen} class have the following methods:
181
182\begin{methoddesc}{poll}{}
183Check if child process has terminated. Returns returncode
184attribute.
185\end{methoddesc}
186
187\begin{methoddesc}{wait}{}
188Wait for child process to terminate. Returns returncode attribute.
189\end{methoddesc}
190
191\begin{methoddesc}{communicate}{input=None}
192Interact with process: Send data to stdin. Read data from stdout and
193stderr, until end-of-file is reached. Wait for process to terminate.
Walter Dörwald769f8212005-04-14 20:08:59 +0000194The optional \var{input} argument should be a string to be sent to the
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000195child process, or \code{None}, if no data should be sent to the child.
196
197communicate() returns a tuple (stdout, stderr).
198
199\note{The data read is buffered in memory, so do not use this method
200if the data size is large or unlimited.}
201\end{methoddesc}
202
203The following attributes are also available:
204
205\begin{memberdesc}{stdin}
206If the \var{stdin} argument is \code{PIPE}, this attribute is a file
207object that provides input to the child process. Otherwise, it is
208\code{None}.
209\end{memberdesc}
210
211\begin{memberdesc}{stdout}
212If the \var{stdout} argument is \code{PIPE}, this attribute is a file
213object that provides output from the child process. Otherwise, it is
214\code{None}.
215\end{memberdesc}
216
217\begin{memberdesc}{stderr}
218If the \var{stderr} argument is \code{PIPE}, this attribute is file
219object that provides error output from the child process. Otherwise,
220it is \code{None}.
221\end{memberdesc}
222
223\begin{memberdesc}{pid}
224The process ID of the child process.
225\end{memberdesc}
226
227\begin{memberdesc}{returncode}
228The child return code. A \code{None} value indicates that the process
229hasn't terminated yet. A negative value -N indicates that the child
230was terminated by signal N (\UNIX{} only).
231\end{memberdesc}
232
233
234\subsection{Replacing Older Functions with the subprocess Module}
235
236In this section, "a ==> b" means that b can be used as a replacement
237for a.
238
239\note{All functions in this section fail (more or less) silently if
240the executed program cannot be found; this module raises an
241\exception{OSError} exception.}
242
243In the following examples, we assume that the subprocess module is
244imported with "from subprocess import *".
245
246\subsubsection{Replacing /bin/sh shell backquote}
247
248\begin{verbatim}
249output=`mycmd myarg`
250==>
251output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
252\end{verbatim}
253
254\subsubsection{Replacing shell pipe line}
255
256\begin{verbatim}
257output=`dmesg | grep hda`
258==>
259p1 = Popen(["dmesg"], stdout=PIPE)
Peter Astrand6fdf3cb2004-11-30 18:06:42 +0000260p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000261output = p2.communicate()[0]
262\end{verbatim}
263
264\subsubsection{Replacing os.system()}
265
266\begin{verbatim}
267sts = os.system("mycmd" + " myarg")
268==>
269p = Popen("mycmd" + " myarg", shell=True)
270sts = os.waitpid(p.pid, 0)
271\end{verbatim}
272
273Notes:
274
275\begin{itemize}
276\item Calling the program through the shell is usually not required.
277\item It's easier to look at the \member{returncode} attribute than
278 the exit status.
279\end{itemize}
280
281A more realistic example would look like this:
282
283\begin{verbatim}
284try:
285 retcode = call("mycmd" + " myarg", shell=True)
286 if retcode < 0:
287 print >>sys.stderr, "Child was terminated by signal", -retcode
288 else:
289 print >>sys.stderr, "Child returned", retcode
290except OSError, e:
291 print >>sys.stderr, "Execution failed:", e
292\end{verbatim}
293
294\subsubsection{Replacing os.spawn*}
295
296P_NOWAIT example:
297
298\begin{verbatim}
299pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
300==>
301pid = Popen(["/bin/mycmd", "myarg"]).pid
302\end{verbatim}
303
304P_WAIT example:
305
306\begin{verbatim}
307retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
308==>
309retcode = call(["/bin/mycmd", "myarg"])
310\end{verbatim}
311
312Vector example:
313
314\begin{verbatim}
315os.spawnvp(os.P_NOWAIT, path, args)
316==>
317Popen([path] + args[1:])
318\end{verbatim}
319
320Environment example:
321
322\begin{verbatim}
323os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
324==>
325Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
326\end{verbatim}
327
328\subsubsection{Replacing os.popen*}
329
330\begin{verbatim}
331pipe = os.popen(cmd, mode='r', bufsize)
332==>
333pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
334\end{verbatim}
335
336\begin{verbatim}
337pipe = os.popen(cmd, mode='w', bufsize)
338==>
339pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
340\end{verbatim}
341
342\begin{verbatim}
343(child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
344==>
345p = Popen(cmd, shell=True, bufsize=bufsize,
346 stdin=PIPE, stdout=PIPE, close_fds=True)
347(child_stdin, child_stdout) = (p.stdin, p.stdout)
348\end{verbatim}
349
350\begin{verbatim}
351(child_stdin,
352 child_stdout,
353 child_stderr) = os.popen3(cmd, mode, bufsize)
354==>
355p = Popen(cmd, shell=True, bufsize=bufsize,
356 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
357(child_stdin,
358 child_stdout,
359 child_stderr) = (p.stdin, p.stdout, p.stderr)
360\end{verbatim}
361
362\begin{verbatim}
363(child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
364==>
365p = Popen(cmd, shell=True, bufsize=bufsize,
366 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
367(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
368\end{verbatim}
369
370\subsubsection{Replacing popen2.*}
371
372\note{If the cmd argument to popen2 functions is a string, the command
373is executed through /bin/sh. If it is a list, the command is directly
374executed.}
375
376\begin{verbatim}
377(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
378==>
Walter Dörwald769f8212005-04-14 20:08:59 +0000379p = Popen(["somestring"], shell=True, bufsize=bufsize,
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000380 stdin=PIPE, stdout=PIPE, close_fds=True)
381(child_stdout, child_stdin) = (p.stdout, p.stdin)
382\end{verbatim}
383
384\begin{verbatim}
385(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
386==>
387p = Popen(["mycmd", "myarg"], bufsize=bufsize,
388 stdin=PIPE, stdout=PIPE, close_fds=True)
389(child_stdout, child_stdin) = (p.stdout, p.stdin)
390\end{verbatim}
391
Neal Norwitzb7b54f72006-02-04 23:00:48 +0000392The popen2.Popen3 and popen2.Popen4 basically works as subprocess.Popen,
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000393except that:
394
395\begin{itemize}
396\item subprocess.Popen raises an exception if the execution fails
397
398\item the \var{capturestderr} argument is replaced with the \var{stderr}
399 argument.
400
401\item stdin=PIPE and stdout=PIPE must be specified.
402
403\item popen2 closes all file descriptors by default, but you have to
404 specify close_fds=True with subprocess.Popen.
405\end{itemize}