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