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