blob: dc386bfb4e7080f150d6637805e3ce18d769ad37 [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}
148\end{funcdesc}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000149
150\subsubsection{Exceptions}
151
152Exceptions raised in the child process, before the new program has
153started to execute, will be re-raised in the parent. Additionally,
154the exception object will have one extra attribute called
155\member{child_traceback}, which is a string containing traceback
156information from the childs point of view.
157
158The most common exception raised is \exception{OSError}. This occurs,
159for example, when trying to execute a non-existent file. Applications
160should prepare for \exception{OSError} exceptions.
161
162A \exception{ValueError} will be raised if \class{Popen} is called
163with invalid arguments.
164
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000165check_call() will raise \exception{CalledProcessError}, if the called
166process returns a non-zero return code.
Peter Astrand454f7672005-01-01 09:36:35 +0000167
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
Guido van Rossumd8faa362007-04-27 19:54:29 +0000180\begin{methoddesc}[Popen]{poll}{}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000181Check if child process has terminated. Returns returncode
182attribute.
183\end{methoddesc}
184
Guido van Rossumd8faa362007-04-27 19:54:29 +0000185\begin{methoddesc}[Popen]{wait}{}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000186Wait for child process to terminate. Returns returncode attribute.
187\end{methoddesc}
188
Guido van Rossumd8faa362007-04-27 19:54:29 +0000189\begin{methoddesc}[Popen]{communicate}{input=None}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000190Interact 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
Guido van Rossumd8faa362007-04-27 19:54:29 +0000203\begin{memberdesc}[Popen]{stdin}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000204If 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
Guido van Rossumd8faa362007-04-27 19:54:29 +0000209\begin{memberdesc}[Popen]{stdout}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000210If 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
Guido van Rossumd8faa362007-04-27 19:54:29 +0000215\begin{memberdesc}[Popen]{stderr}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000216If 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
Guido van Rossumd8faa362007-04-27 19:54:29 +0000221\begin{memberdesc}[Popen]{pid}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000222The process ID of the child process.
223\end{memberdesc}
224
Guido van Rossumd8faa362007-04-27 19:54:29 +0000225\begin{memberdesc}[Popen]{returncode}
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000226The 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
Guido van Rossumb940e112007-01-10 16:19:56 +0000288except OSError as e:
Fredrik Lundhb04b6af2004-10-17 16:29:48 +0000289 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}