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