blob: 35ab4d02b15e70f09ea0e5efed94fcf8440d3827 [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*
Fredrik Lundhb04b6af2004-10-17 16:29:48 +000018commands.*
19\end{verbatim}
20
21Information about how the \module{subprocess} module can be used to
22replace these modules and functions can be found in the following
23sections.
24
25\subsection{Using the subprocess Module}
26
27This module defines one class called \class{Popen}:
28
29\begin{classdesc}{Popen}{args, bufsize=0, executable=None,
30 stdin=None, stdout=None, stderr=None,
31 preexec_fn=None, close_fds=False, shell=False,
32 cwd=None, env=None, universal_newlines=False,
33 startupinfo=None, creationflags=0}
34
35Arguments are:
36
37\var{args} should be a string, or a sequence of program arguments. The
38program to execute is normally the first item in the args sequence or
39string, but can be explicitly set by using the executable argument.
40
41On \UNIX{}, with \var{shell=False} (default): In this case, the Popen
42class uses \method{os.execvp()} to execute the child program.
43\var{args} should normally be a sequence. A string will be treated as a
44sequence with the string as the only item (the program to execute).
45
46On \UNIX{}, with \var{shell=True}: If args is a string, it specifies the
47command string to execute through the shell. If \var{args} is a
48sequence, the first item specifies the command string, and any
49additional items will be treated as additional shell arguments.
50
51On Windows: the \class{Popen} class uses CreateProcess() to execute
52the child program, which operates on strings. If \var{args} is a
53sequence, it will be converted to a string using the
54\method{list2cmdline} method. Please note that not all MS Windows
55applications interpret the command line the same way:
56\method{list2cmdline} is designed for applications using the same
57rules as the MS C runtime.
58
59\var{bufsize}, if given, has the same meaning as the corresponding
60argument to the built-in open() function: \constant{0} means unbuffered,
61\constant{1} means line buffered, any other positive value means use a
62buffer of (approximately) that size. A negative \var{bufsize} means to
63use the system default, which usually means fully buffered. The default
64value for \var{bufsize} is \constant{0} (unbuffered).
65
Peter Astrand35461882004-11-07 16:38:08 +000066The \var{executable} argument specifies the program to execute. It is
67very seldom needed: Usually, the program to execute is defined by the
Thomas Wouters477c8d52006-05-27 19:21:47 +000068\var{args} argument. If \code{shell=True}, the \var{executable}
Peter Astrand35461882004-11-07 16:38:08 +000069argument specifies which shell to use. On \UNIX{}, the default shell
Thomas Wouters477c8d52006-05-27 19:21:47 +000070is \file{/bin/sh}. On Windows, the default shell is specified by the
71\envvar{COMSPEC} environment variable.
Peter Astrand35461882004-11-07 16:38:08 +000072
Fredrik Lundhb04b6af2004-10-17 16:29:48 +000073\var{stdin}, \var{stdout} and \var{stderr} specify the executed
74programs' standard input, standard output and standard error file
75handles, respectively. Valid values are \code{PIPE}, an existing file
76descriptor (a positive integer), an existing file object, and
77\code{None}. \code{PIPE} indicates that a new pipe to the child
78should be created. With \code{None}, no redirection will occur; the
79child's file handles will be inherited from the parent. Additionally,
80\var{stderr} can be \code{STDOUT}, which indicates that the stderr
81data from the applications should be captured into the same file
82handle as for stdout.
83
84If \var{preexec_fn} is set to a callable object, this object will be
85called in the child process just before the child is executed.
Thomas Wouters477c8d52006-05-27 19:21:47 +000086(\UNIX{} only)
Fredrik Lundhb04b6af2004-10-17 16:29:48 +000087
88If \var{close_fds} is true, all file descriptors except \constant{0},
89\constant{1} and \constant{2} will be closed before the child process is
Thomas Wouters477c8d52006-05-27 19:21:47 +000090executed. (\UNIX{} only)
Fredrik Lundhb04b6af2004-10-17 16:29:48 +000091
92If \var{shell} is \constant{True}, the specified command will be
93executed through the shell.
94
Thomas Wouters477c8d52006-05-27 19:21:47 +000095If \var{cwd} is not \code{None}, the child's current directory will be
96changed to \var{cwd} before it is executed. Note that this directory
97is not considered when searching the executable, so you can't specify
98the program's path relative to \var{cwd}.
Fredrik Lundhb04b6af2004-10-17 16:29:48 +000099
100If \var{env} is not \code{None}, it defines the environment variables
101for the new process.
102
103If \var{universal_newlines} is \constant{True}, the file objects stdout
Georg Brandl0f194232006-01-01 21:35:20 +0000104and stderr are opened as text files, but lines may be terminated by
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000105any of \code{'\e n'}, the \UNIX{} end-of-line convention, \code{'\e r'},
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000106the Macintosh convention or \code{'\e r\e n'}, the Windows convention.
107All of these external representations are seen as \code{'\e n'} by the
108Python program. \note{This feature is only available if Python is built
109with universal newline support (the default). Also, the newlines
110attribute of the file objects \member{stdout}, \member{stdin} and
111\member{stderr} are not updated by the communicate() method.}
112
113The \var{startupinfo} and \var{creationflags}, if given, will be
114passed to the underlying CreateProcess() function. They can specify
115things such as appearance of the main window and priority for the new
116process. (Windows only)
117\end{classdesc}
118
119\subsubsection{Convenience Functions}
120
Peter Astrand454f7672005-01-01 09:36:35 +0000121This module also defines two shortcut functions:
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000122
Peter Astrand5f5e1412004-12-05 20:15:36 +0000123\begin{funcdesc}{call}{*popenargs, **kwargs}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000124Run command with arguments. Wait for command to complete, then
125return the \member{returncode} attribute.
126
127The arguments are the same as for the Popen constructor. Example:
128
129\begin{verbatim}
130 retcode = call(["ls", "-l"])
131\end{verbatim}
132\end{funcdesc}
133
Peter Astrand454f7672005-01-01 09:36:35 +0000134\begin{funcdesc}{check_call}{*popenargs, **kwargs}
135Run command with arguments. Wait for command to complete. If the exit
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000136code was zero then return, otherwise raise \exception{CalledProcessError.}
137The \exception{CalledProcessError} object will have the return code in the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000138\member{returncode} attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000139
140The arguments are the same as for the Popen constructor. Example:
141
142\begin{verbatim}
143 check_call(["ls", "-l"])
144\end{verbatim}
145\end{funcdesc}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000146
147\subsubsection{Exceptions}
148
149Exceptions raised in the child process, before the new program has
150started to execute, will be re-raised in the parent. Additionally,
151the exception object will have one extra attribute called
152\member{child_traceback}, which is a string containing traceback
153information from the childs point of view.
154
155The most common exception raised is \exception{OSError}. This occurs,
156for example, when trying to execute a non-existent file. Applications
157should prepare for \exception{OSError} exceptions.
158
159A \exception{ValueError} will be raised if \class{Popen} is called
160with invalid arguments.
161
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000162check_call() will raise \exception{CalledProcessError}, if the called
163process returns a non-zero return code.
Peter Astrand454f7672005-01-01 09:36:35 +0000164
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000165
166\subsubsection{Security}
167
168Unlike some other popen functions, this implementation will never call
169/bin/sh implicitly. This means that all characters, including shell
170metacharacters, can safely be passed to child processes.
171
172
173\subsection{Popen Objects}
174
175Instances of the \class{Popen} class have the following methods:
176
Guido van Rossumd8faa362007-04-27 19:54:29 +0000177\begin{methoddesc}[Popen]{poll}{}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000178Check if child process has terminated. Returns returncode
179attribute.
180\end{methoddesc}
181
Guido van Rossumd8faa362007-04-27 19:54:29 +0000182\begin{methoddesc}[Popen]{wait}{}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000183Wait for child process to terminate. Returns returncode attribute.
184\end{methoddesc}
185
Guido van Rossumd8faa362007-04-27 19:54:29 +0000186\begin{methoddesc}[Popen]{communicate}{input=None}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000187Interact with process: Send data to stdin. Read data from stdout and
188stderr, until end-of-file is reached. Wait for process to terminate.
Walter Dörwald769f8212005-04-14 20:08:59 +0000189The optional \var{input} argument should be a string to be sent to the
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000190child process, or \code{None}, if no data should be sent to the child.
191
192communicate() returns a tuple (stdout, stderr).
193
194\note{The data read is buffered in memory, so do not use this method
195if the data size is large or unlimited.}
196\end{methoddesc}
197
198The following attributes are also available:
199
Guido van Rossumd8faa362007-04-27 19:54:29 +0000200\begin{memberdesc}[Popen]{stdin}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000201If the \var{stdin} argument is \code{PIPE}, this attribute is a file
202object that provides input to the child process. Otherwise, it is
203\code{None}.
204\end{memberdesc}
205
Guido van Rossumd8faa362007-04-27 19:54:29 +0000206\begin{memberdesc}[Popen]{stdout}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000207If the \var{stdout} argument is \code{PIPE}, this attribute is a file
208object that provides output from the child process. Otherwise, it is
209\code{None}.
210\end{memberdesc}
211
Guido van Rossumd8faa362007-04-27 19:54:29 +0000212\begin{memberdesc}[Popen]{stderr}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000213If the \var{stderr} argument is \code{PIPE}, this attribute is file
214object that provides error output from the child process. Otherwise,
215it is \code{None}.
216\end{memberdesc}
217
Guido van Rossumd8faa362007-04-27 19:54:29 +0000218\begin{memberdesc}[Popen]{pid}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000219The process ID of the child process.
220\end{memberdesc}
221
Guido van Rossumd8faa362007-04-27 19:54:29 +0000222\begin{memberdesc}[Popen]{returncode}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000223The child return code. A \code{None} value indicates that the process
224hasn't terminated yet. A negative value -N indicates that the child
225was terminated by signal N (\UNIX{} only).
226\end{memberdesc}
227
228
229\subsection{Replacing Older Functions with the subprocess Module}
230
231In this section, "a ==> b" means that b can be used as a replacement
232for a.
233
234\note{All functions in this section fail (more or less) silently if
235the executed program cannot be found; this module raises an
236\exception{OSError} exception.}
237
238In the following examples, we assume that the subprocess module is
239imported with "from subprocess import *".
240
241\subsubsection{Replacing /bin/sh shell backquote}
242
243\begin{verbatim}
244output=`mycmd myarg`
245==>
246output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
247\end{verbatim}
248
249\subsubsection{Replacing shell pipe line}
250
251\begin{verbatim}
252output=`dmesg | grep hda`
253==>
254p1 = Popen(["dmesg"], stdout=PIPE)
Peter Astrand6fdf3cb2004-11-30 18:06:42 +0000255p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000256output = p2.communicate()[0]
257\end{verbatim}
258
259\subsubsection{Replacing os.system()}
260
261\begin{verbatim}
262sts = os.system("mycmd" + " myarg")
263==>
264p = Popen("mycmd" + " myarg", shell=True)
265sts = os.waitpid(p.pid, 0)
266\end{verbatim}
267
268Notes:
269
270\begin{itemize}
271\item Calling the program through the shell is usually not required.
272\item It's easier to look at the \member{returncode} attribute than
273 the exit status.
274\end{itemize}
275
276A more realistic example would look like this:
277
278\begin{verbatim}
279try:
280 retcode = call("mycmd" + " myarg", shell=True)
281 if retcode < 0:
282 print >>sys.stderr, "Child was terminated by signal", -retcode
283 else:
284 print >>sys.stderr, "Child returned", retcode
Guido van Rossumb940e112007-01-10 16:19:56 +0000285except OSError as e:
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000286 print >>sys.stderr, "Execution failed:", e
287\end{verbatim}
288
289\subsubsection{Replacing os.spawn*}
290
291P_NOWAIT example:
292
293\begin{verbatim}
294pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
295==>
296pid = Popen(["/bin/mycmd", "myarg"]).pid
297\end{verbatim}
298
299P_WAIT example:
300
301\begin{verbatim}
302retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
303==>
304retcode = call(["/bin/mycmd", "myarg"])
305\end{verbatim}
306
307Vector example:
308
309\begin{verbatim}
310os.spawnvp(os.P_NOWAIT, path, args)
311==>
312Popen([path] + args[1:])
313\end{verbatim}
314
315Environment example:
316
317\begin{verbatim}
318os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
319==>
320Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
321\end{verbatim}
322
323\subsubsection{Replacing os.popen*}
324
325\begin{verbatim}
326pipe = os.popen(cmd, mode='r', bufsize)
327==>
328pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
329\end{verbatim}
330
331\begin{verbatim}
332pipe = os.popen(cmd, mode='w', bufsize)
333==>
334pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
335\end{verbatim}