blob: e2a9bb659720e0cc70ff996e0e3ab92f61e11212 [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
Guido van Rossume7ba4952007-06-06 23:52:48 +000090executed. (\UNIX{} only). Or, on Windows, if \var{close_fds} is true
91then no handles will be inherited by the child process. Note that on
92Windows, you cannot set \var{close_fds} to true and also redirect the
93standard handles by setting \var{stdin}, \var{stdout} or \var{stderr}.
Fredrik Lundhb04b6af2004-10-17 16:29:48 +000094
95If \var{shell} is \constant{True}, the specified command will be
96executed through the shell.
97
Thomas Wouters477c8d52006-05-27 19:21:47 +000098If \var{cwd} is not \code{None}, the child's current directory will be
99changed to \var{cwd} before it is executed. Note that this directory
100is not considered when searching the executable, so you can't specify
101the program's path relative to \var{cwd}.
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000102
103If \var{env} is not \code{None}, it defines the environment variables
104for the new process.
105
106If \var{universal_newlines} is \constant{True}, the file objects stdout
Georg Brandl0f194232006-01-01 21:35:20 +0000107and stderr are opened as text files, but lines may be terminated by
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000108any of \code{'\e n'}, the \UNIX{} end-of-line convention, \code{'\e r'},
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000109the Macintosh convention or \code{'\e r\e n'}, the Windows convention.
110All of these external representations are seen as \code{'\e n'} by the
111Python program. \note{This feature is only available if Python is built
112with universal newline support (the default). Also, the newlines
113attribute of the file objects \member{stdout}, \member{stdin} and
114\member{stderr} are not updated by the communicate() method.}
115
116The \var{startupinfo} and \var{creationflags}, if given, will be
117passed to the underlying CreateProcess() function. They can specify
118things such as appearance of the main window and priority for the new
119process. (Windows only)
120\end{classdesc}
121
122\subsubsection{Convenience Functions}
123
Peter Astrand454f7672005-01-01 09:36:35 +0000124This module also defines two shortcut functions:
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000125
Peter Astrand5f5e1412004-12-05 20:15:36 +0000126\begin{funcdesc}{call}{*popenargs, **kwargs}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000127Run command with arguments. Wait for command to complete, then
128return the \member{returncode} attribute.
129
130The arguments are the same as for the Popen constructor. Example:
131
132\begin{verbatim}
133 retcode = call(["ls", "-l"])
134\end{verbatim}
135\end{funcdesc}
136
Peter Astrand454f7672005-01-01 09:36:35 +0000137\begin{funcdesc}{check_call}{*popenargs, **kwargs}
138Run command with arguments. Wait for command to complete. If the exit
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000139code was zero then return, otherwise raise \exception{CalledProcessError.}
140The \exception{CalledProcessError} object will have the return code in the
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000141\member{returncode} attribute.
Peter Astrand454f7672005-01-01 09:36:35 +0000142
143The arguments are the same as for the Popen constructor. Example:
144
145\begin{verbatim}
146 check_call(["ls", "-l"])
147\end{verbatim}
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000148
149\versionadded{2.5}
Peter Astrand454f7672005-01-01 09:36:35 +0000150\end{funcdesc}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000151
152\subsubsection{Exceptions}
153
154Exceptions raised in the child process, before the new program has
155started to execute, will be re-raised in the parent. Additionally,
156the exception object will have one extra attribute called
157\member{child_traceback}, which is a string containing traceback
158information from the childs point of view.
159
160The most common exception raised is \exception{OSError}. This occurs,
161for example, when trying to execute a non-existent file. Applications
162should prepare for \exception{OSError} exceptions.
163
164A \exception{ValueError} will be raised if \class{Popen} is called
165with invalid arguments.
166
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000167check_call() will raise \exception{CalledProcessError}, if the called
168process returns a non-zero return code.
Peter Astrand454f7672005-01-01 09:36:35 +0000169
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000170
171\subsubsection{Security}
172
173Unlike some other popen functions, this implementation will never call
174/bin/sh implicitly. This means that all characters, including shell
175metacharacters, can safely be passed to child processes.
176
177
178\subsection{Popen Objects}
179
180Instances of the \class{Popen} class have the following methods:
181
Guido van Rossumd8faa362007-04-27 19:54:29 +0000182\begin{methoddesc}[Popen]{poll}{}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000183Check if child process has terminated. Returns returncode
184attribute.
185\end{methoddesc}
186
Guido van Rossumd8faa362007-04-27 19:54:29 +0000187\begin{methoddesc}[Popen]{wait}{}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000188Wait for child process to terminate. Returns returncode attribute.
189\end{methoddesc}
190
Guido van Rossumd8faa362007-04-27 19:54:29 +0000191\begin{methoddesc}[Popen]{communicate}{input=None}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000192Interact with process: Send data to stdin. Read data from stdout and
193stderr, until end-of-file is reached. Wait for process to terminate.
Walter Dörwald769f8212005-04-14 20:08:59 +0000194The optional \var{input} argument should be a string to be sent to the
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000195child process, or \code{None}, if no data should be sent to the child.
196
197communicate() returns a tuple (stdout, stderr).
198
199\note{The data read is buffered in memory, so do not use this method
200if the data size is large or unlimited.}
201\end{methoddesc}
202
203The following attributes are also available:
204
Guido van Rossumd8faa362007-04-27 19:54:29 +0000205\begin{memberdesc}[Popen]{stdin}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000206If the \var{stdin} argument is \code{PIPE}, this attribute is a file
207object that provides input to the child process. Otherwise, it is
208\code{None}.
209\end{memberdesc}
210
Guido van Rossumd8faa362007-04-27 19:54:29 +0000211\begin{memberdesc}[Popen]{stdout}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000212If the \var{stdout} argument is \code{PIPE}, this attribute is a file
213object that provides output from the child process. Otherwise, it is
214\code{None}.
215\end{memberdesc}
216
Guido van Rossumd8faa362007-04-27 19:54:29 +0000217\begin{memberdesc}[Popen]{stderr}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000218If the \var{stderr} argument is \code{PIPE}, this attribute is file
219object that provides error output from the child process. Otherwise,
220it is \code{None}.
221\end{memberdesc}
222
Guido van Rossumd8faa362007-04-27 19:54:29 +0000223\begin{memberdesc}[Popen]{pid}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000224The process ID of the child process.
225\end{memberdesc}
226
Guido van Rossumd8faa362007-04-27 19:54:29 +0000227\begin{memberdesc}[Popen]{returncode}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000228The child return code. A \code{None} value indicates that the process
229hasn't terminated yet. A negative value -N indicates that the child
230was terminated by signal N (\UNIX{} only).
231\end{memberdesc}
232
233
234\subsection{Replacing Older Functions with the subprocess Module}
235
236In this section, "a ==> b" means that b can be used as a replacement
237for a.
238
239\note{All functions in this section fail (more or less) silently if
240the executed program cannot be found; this module raises an
241\exception{OSError} exception.}
242
243In the following examples, we assume that the subprocess module is
244imported with "from subprocess import *".
245
246\subsubsection{Replacing /bin/sh shell backquote}
247
248\begin{verbatim}
249output=`mycmd myarg`
250==>
251output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
252\end{verbatim}
253
254\subsubsection{Replacing shell pipe line}
255
256\begin{verbatim}
257output=`dmesg | grep hda`
258==>
259p1 = Popen(["dmesg"], stdout=PIPE)
Peter Astrand6fdf3cb2004-11-30 18:06:42 +0000260p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000261output = p2.communicate()[0]
262\end{verbatim}
263
264\subsubsection{Replacing os.system()}
265
266\begin{verbatim}
267sts = os.system("mycmd" + " myarg")
268==>
269p = Popen("mycmd" + " myarg", shell=True)
270sts = os.waitpid(p.pid, 0)
271\end{verbatim}
272
273Notes:
274
275\begin{itemize}
276\item Calling the program through the shell is usually not required.
277\item It's easier to look at the \member{returncode} attribute than
278 the exit status.
279\end{itemize}
280
281A more realistic example would look like this:
282
283\begin{verbatim}
284try:
285 retcode = call("mycmd" + " myarg", shell=True)
286 if retcode < 0:
287 print >>sys.stderr, "Child was terminated by signal", -retcode
288 else:
289 print >>sys.stderr, "Child returned", retcode
Guido van Rossumb940e112007-01-10 16:19:56 +0000290except OSError as e:
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000291 print >>sys.stderr, "Execution failed:", e
292\end{verbatim}
293
294\subsubsection{Replacing os.spawn*}
295
296P_NOWAIT example:
297
298\begin{verbatim}
299pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
300==>
301pid = Popen(["/bin/mycmd", "myarg"]).pid
302\end{verbatim}
303
304P_WAIT example:
305
306\begin{verbatim}
307retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
308==>
309retcode = call(["/bin/mycmd", "myarg"])
310\end{verbatim}
311
312Vector example:
313
314\begin{verbatim}
315os.spawnvp(os.P_NOWAIT, path, args)
316==>
317Popen([path] + args[1:])
318\end{verbatim}
319
320Environment example:
321
322\begin{verbatim}
323os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
324==>
325Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
326\end{verbatim}
327
328\subsubsection{Replacing os.popen*}
329
330\begin{verbatim}
331pipe = os.popen(cmd, mode='r', bufsize)
332==>
333pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
334\end{verbatim}
335
336\begin{verbatim}
337pipe = os.popen(cmd, mode='w', bufsize)
338==>
339pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
340\end{verbatim}