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