blob: 14e68aa200c53b18ceb3820175681209c4a80880 [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
71\var{stdin}, \var{stdout} and \var{stderr} specify the executed
72programs' standard input, standard output and standard error file
73handles, respectively. Valid values are \code{PIPE}, an existing file
74descriptor (a positive integer), an existing file object, and
75\code{None}. \code{PIPE} indicates that a new pipe to the child
76should be created. With \code{None}, no redirection will occur; the
77child's file handles will be inherited from the parent. Additionally,
78\var{stderr} can be \code{STDOUT}, which indicates that the stderr
79data from the applications should be captured into the same file
80handle as for stdout.
81
82If \var{preexec_fn} is set to a callable object, this object will be
83called in the child process just before the child is executed.
84
85If \var{close_fds} is true, all file descriptors except \constant{0},
86\constant{1} and \constant{2} will be closed before the child process is
87executed.
88
89If \var{shell} is \constant{True}, the specified command will be
90executed through the shell.
91
92If \var{cwd} is not \code{None}, the current directory will be changed
93to cwd before the child is executed.
94
95If \var{env} is not \code{None}, it defines the environment variables
96for the new process.
97
98If \var{universal_newlines} is \constant{True}, the file objects stdout
99and stderr are opened as a text files, but lines may be terminated by
100any of \code{'\e n'}, the Unix end-of-line convention, \code{'\e r'},
101the Macintosh convention or \code{'\e r\e n'}, the Windows convention.
102All of these external representations are seen as \code{'\e n'} by the
103Python program. \note{This feature is only available if Python is built
104with universal newline support (the default). Also, the newlines
105attribute of the file objects \member{stdout}, \member{stdin} and
106\member{stderr} are not updated by the communicate() method.}
107
108The \var{startupinfo} and \var{creationflags}, if given, will be
109passed to the underlying CreateProcess() function. They can specify
110things such as appearance of the main window and priority for the new
111process. (Windows only)
112\end{classdesc}
113
114\subsubsection{Convenience Functions}
115
116This module also defines one shortcut function:
117
118\begin{funcdesc}{call}{*args, **kwargs}
119Run command with arguments. Wait for command to complete, then
120return the \member{returncode} attribute.
121
122The arguments are the same as for the Popen constructor. Example:
123
124\begin{verbatim}
125 retcode = call(["ls", "-l"])
126\end{verbatim}
127\end{funcdesc}
128
129
130\subsubsection{Exceptions}
131
132Exceptions raised in the child process, before the new program has
133started to execute, will be re-raised in the parent. Additionally,
134the exception object will have one extra attribute called
135\member{child_traceback}, which is a string containing traceback
136information from the childs point of view.
137
138The most common exception raised is \exception{OSError}. This occurs,
139for example, when trying to execute a non-existent file. Applications
140should prepare for \exception{OSError} exceptions.
141
142A \exception{ValueError} will be raised if \class{Popen} is called
143with invalid arguments.
144
145
146\subsubsection{Security}
147
148Unlike some other popen functions, this implementation will never call
149/bin/sh implicitly. This means that all characters, including shell
150metacharacters, can safely be passed to child processes.
151
152
153\subsection{Popen Objects}
154
155Instances of the \class{Popen} class have the following methods:
156
157\begin{methoddesc}{poll}{}
158Check if child process has terminated. Returns returncode
159attribute.
160\end{methoddesc}
161
162\begin{methoddesc}{wait}{}
163Wait for child process to terminate. Returns returncode attribute.
164\end{methoddesc}
165
166\begin{methoddesc}{communicate}{input=None}
167Interact with process: Send data to stdin. Read data from stdout and
168stderr, until end-of-file is reached. Wait for process to terminate.
169The optional \var{stdin} argument should be a string to be sent to the
170child process, or \code{None}, if no data should be sent to the child.
171
172communicate() returns a tuple (stdout, stderr).
173
174\note{The data read is buffered in memory, so do not use this method
175if the data size is large or unlimited.}
176\end{methoddesc}
177
178The following attributes are also available:
179
180\begin{memberdesc}{stdin}
181If the \var{stdin} argument is \code{PIPE}, this attribute is a file
182object that provides input to the child process. Otherwise, it is
183\code{None}.
184\end{memberdesc}
185
186\begin{memberdesc}{stdout}
187If the \var{stdout} argument is \code{PIPE}, this attribute is a file
188object that provides output from the child process. Otherwise, it is
189\code{None}.
190\end{memberdesc}
191
192\begin{memberdesc}{stderr}
193If the \var{stderr} argument is \code{PIPE}, this attribute is file
194object that provides error output from the child process. Otherwise,
195it is \code{None}.
196\end{memberdesc}
197
198\begin{memberdesc}{pid}
199The process ID of the child process.
200\end{memberdesc}
201
202\begin{memberdesc}{returncode}
203The child return code. A \code{None} value indicates that the process
204hasn't terminated yet. A negative value -N indicates that the child
205was terminated by signal N (\UNIX{} only).
206\end{memberdesc}
207
208
209\subsection{Replacing Older Functions with the subprocess Module}
210
211In this section, "a ==> b" means that b can be used as a replacement
212for a.
213
214\note{All functions in this section fail (more or less) silently if
215the executed program cannot be found; this module raises an
216\exception{OSError} exception.}
217
218In the following examples, we assume that the subprocess module is
219imported with "from subprocess import *".
220
221\subsubsection{Replacing /bin/sh shell backquote}
222
223\begin{verbatim}
224output=`mycmd myarg`
225==>
226output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
227\end{verbatim}
228
229\subsubsection{Replacing shell pipe line}
230
231\begin{verbatim}
232output=`dmesg | grep hda`
233==>
234p1 = Popen(["dmesg"], stdout=PIPE)
235p2 = Popen(["grep", "hda"], stdin=p1.stdout)
236output = p2.communicate()[0]
237\end{verbatim}
238
239\subsubsection{Replacing os.system()}
240
241\begin{verbatim}
242sts = os.system("mycmd" + " myarg")
243==>
244p = Popen("mycmd" + " myarg", shell=True)
245sts = os.waitpid(p.pid, 0)
246\end{verbatim}
247
248Notes:
249
250\begin{itemize}
251\item Calling the program through the shell is usually not required.
252\item It's easier to look at the \member{returncode} attribute than
253 the exit status.
254\end{itemize}
255
256A more realistic example would look like this:
257
258\begin{verbatim}
259try:
260 retcode = call("mycmd" + " myarg", shell=True)
261 if retcode < 0:
262 print >>sys.stderr, "Child was terminated by signal", -retcode
263 else:
264 print >>sys.stderr, "Child returned", retcode
265except OSError, e:
266 print >>sys.stderr, "Execution failed:", e
267\end{verbatim}
268
269\subsubsection{Replacing os.spawn*}
270
271P_NOWAIT example:
272
273\begin{verbatim}
274pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
275==>
276pid = Popen(["/bin/mycmd", "myarg"]).pid
277\end{verbatim}
278
279P_WAIT example:
280
281\begin{verbatim}
282retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
283==>
284retcode = call(["/bin/mycmd", "myarg"])
285\end{verbatim}
286
287Vector example:
288
289\begin{verbatim}
290os.spawnvp(os.P_NOWAIT, path, args)
291==>
292Popen([path] + args[1:])
293\end{verbatim}
294
295Environment example:
296
297\begin{verbatim}
298os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
299==>
300Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
301\end{verbatim}
302
303\subsubsection{Replacing os.popen*}
304
305\begin{verbatim}
306pipe = os.popen(cmd, mode='r', bufsize)
307==>
308pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
309\end{verbatim}
310
311\begin{verbatim}
312pipe = os.popen(cmd, mode='w', bufsize)
313==>
314pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
315\end{verbatim}
316
317\begin{verbatim}
318(child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
319==>
320p = Popen(cmd, shell=True, bufsize=bufsize,
321 stdin=PIPE, stdout=PIPE, close_fds=True)
322(child_stdin, child_stdout) = (p.stdin, p.stdout)
323\end{verbatim}
324
325\begin{verbatim}
326(child_stdin,
327 child_stdout,
328 child_stderr) = os.popen3(cmd, mode, bufsize)
329==>
330p = Popen(cmd, shell=True, bufsize=bufsize,
331 stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
332(child_stdin,
333 child_stdout,
334 child_stderr) = (p.stdin, p.stdout, p.stderr)
335\end{verbatim}
336
337\begin{verbatim}
338(child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
339==>
340p = Popen(cmd, shell=True, bufsize=bufsize,
341 stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
342(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
343\end{verbatim}
344
345\subsubsection{Replacing popen2.*}
346
347\note{If the cmd argument to popen2 functions is a string, the command
348is executed through /bin/sh. If it is a list, the command is directly
349executed.}
350
351\begin{verbatim}
352(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
353==>
354p = Popen(["somestring"], shell=True, bufsize=bufsize
355 stdin=PIPE, stdout=PIPE, close_fds=True)
356(child_stdout, child_stdin) = (p.stdout, p.stdin)
357\end{verbatim}
358
359\begin{verbatim}
360(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
361==>
362p = Popen(["mycmd", "myarg"], bufsize=bufsize,
363 stdin=PIPE, stdout=PIPE, close_fds=True)
364(child_stdout, child_stdin) = (p.stdout, p.stdin)
365\end{verbatim}
366
367The popen2.Popen3 and popen3.Popen4 basically works as subprocess.Popen,
368except that:
369
370\begin{itemize}
371\item subprocess.Popen raises an exception if the execution fails
372
373\item the \var{capturestderr} argument is replaced with the \var{stderr}
374 argument.
375
376\item stdin=PIPE and stdout=PIPE must be specified.
377
378\item popen2 closes all file descriptors by default, but you have to
379 specify close_fds=True with subprocess.Popen.
380\end{itemize}