|
| 1 | +\section{\module{subprocess} --- Subprocess management} |
| 2 | + |
| 3 | +\declaremodule{standard}{subprocess} |
| 4 | +\modulesynopsis{Subprocess management.} |
| 5 | +\moduleauthor{Peter \AA strand}{ [email protected]} |
| 6 | +\sectionauthor{Peter \AA strand}{ [email protected]} |
| 7 | + |
| 8 | +\versionadded{2.4} |
| 9 | + |
| 10 | +The \module{subprocess} module allows you to spawn new processes, |
| 11 | +connect to their input/output/error pipes, and obtain their return |
| 12 | +codes. This module intends to replace several other, older modules |
| 13 | +and 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} |
| 19 | +os.system |
| 20 | +os.spawn* |
| 21 | +os.popen* |
| 22 | +popen2.* |
| 23 | +commands.* |
| 24 | +\end{verbatim} |
| 25 | + |
| 26 | +Information about how the \module{subprocess} module can be used to |
| 27 | +replace these modules and functions can be found in the following |
| 28 | +sections. |
| 29 | + |
| 30 | +\subsection{Using the subprocess Module} |
| 31 | + |
| 32 | +This 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 | + |
| 40 | +Arguments are: |
| 41 | + |
| 42 | +\var{args} should be a string, or a sequence of program arguments. The |
| 43 | +program to execute is normally the first item in the args sequence or |
| 44 | +string, but can be explicitly set by using the executable argument. |
| 45 | + |
| 46 | +On \UNIX{}, with \var{shell=False} (default): In this case, the Popen |
| 47 | +class uses \method{os.execvp()} to execute the child program. |
| 48 | +\var{args} should normally be a sequence. A string will be treated as a |
| 49 | +sequence with the string as the only item (the program to execute). |
| 50 | + |
| 51 | +On \UNIX{}, with \var{shell=True}: If args is a string, it specifies the |
| 52 | +command string to execute through the shell. If \var{args} is a |
| 53 | +sequence, the first item specifies the command string, and any |
| 54 | +additional items will be treated as additional shell arguments. |
| 55 | + |
| 56 | +On Windows: the \class{Popen} class uses CreateProcess() to execute |
| 57 | +the child program, which operates on strings. If \var{args} is a |
| 58 | +sequence, it will be converted to a string using the |
| 59 | +\method{list2cmdline} method. Please note that not all MS Windows |
| 60 | +applications interpret the command line the same way: |
| 61 | +\method{list2cmdline} is designed for applications using the same |
| 62 | +rules as the MS C runtime. |
| 63 | + |
| 64 | +\var{bufsize}, if given, has the same meaning as the corresponding |
| 65 | +argument to the built-in open() function: \constant{0} means unbuffered, |
| 66 | +\constant{1} means line buffered, any other positive value means use a |
| 67 | +buffer of (approximately) that size. A negative \var{bufsize} means to |
| 68 | +use the system default, which usually means fully buffered. The default |
| 69 | +value for \var{bufsize} is \constant{0} (unbuffered). |
| 70 | + |
| 71 | +\var{stdin}, \var{stdout} and \var{stderr} specify the executed |
| 72 | +programs' standard input, standard output and standard error file |
| 73 | +handles, respectively. Valid values are \code{PIPE}, an existing file |
| 74 | +descriptor (a positive integer), an existing file object, and |
| 75 | +\code{None}. \code{PIPE} indicates that a new pipe to the child |
| 76 | +should be created. With \code{None}, no redirection will occur; the |
| 77 | +child's file handles will be inherited from the parent. Additionally, |
| 78 | +\var{stderr} can be \code{STDOUT}, which indicates that the stderr |
| 79 | +data from the applications should be captured into the same file |
| 80 | +handle as for stdout. |
| 81 | + |
| 82 | +If \var{preexec_fn} is set to a callable object, this object will be |
| 83 | +called in the child process just before the child is executed. |
| 84 | + |
| 85 | +If \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 |
| 87 | +executed. |
| 88 | + |
| 89 | +If \var{shell} is \constant{True}, the specified command will be |
| 90 | +executed through the shell. |
| 91 | + |
| 92 | +If \var{cwd} is not \code{None}, the current directory will be changed |
| 93 | +to cwd before the child is executed. |
| 94 | + |
| 95 | +If \var{env} is not \code{None}, it defines the environment variables |
| 96 | +for the new process. |
| 97 | + |
| 98 | +If \var{universal_newlines} is \constant{True}, the file objects stdout |
| 99 | +and stderr are opened as a text files, but lines may be terminated by |
| 100 | +any of \code{'\e n'}, the Unix end-of-line convention, \code{'\e r'}, |
| 101 | +the Macintosh convention or \code{'\e r\e n'}, the Windows convention. |
| 102 | +All of these external representations are seen as \code{'\e n'} by the |
| 103 | +Python program. \note{This feature is only available if Python is built |
| 104 | +with universal newline support (the default). Also, the newlines |
| 105 | +attribute of the file objects \member{stdout}, \member{stdin} and |
| 106 | +\member{stderr} are not updated by the communicate() method.} |
| 107 | + |
| 108 | +The \var{startupinfo} and \var{creationflags}, if given, will be |
| 109 | +passed to the underlying CreateProcess() function. They can specify |
| 110 | +things such as appearance of the main window and priority for the new |
| 111 | +process. (Windows only) |
| 112 | +\end{classdesc} |
| 113 | + |
| 114 | +\subsubsection{Convenience Functions} |
| 115 | + |
| 116 | +This module also defines one shortcut function: |
| 117 | + |
| 118 | +\begin{funcdesc}{call}{*args, **kwargs} |
| 119 | +Run command with arguments. Wait for command to complete, then |
| 120 | +return the \member{returncode} attribute. |
| 121 | + |
| 122 | +The 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 | + |
| 132 | +Exceptions raised in the child process, before the new program has |
| 133 | +started to execute, will be re-raised in the parent. Additionally, |
| 134 | +the exception object will have one extra attribute called |
| 135 | +\member{child_traceback}, which is a string containing traceback |
| 136 | +information from the childs point of view. |
| 137 | + |
| 138 | +The most common exception raised is \exception{OSError}. This occurs, |
| 139 | +for example, when trying to execute a non-existent file. Applications |
| 140 | +should prepare for \exception{OSError} exceptions. |
| 141 | + |
| 142 | +A \exception{ValueError} will be raised if \class{Popen} is called |
| 143 | +with invalid arguments. |
| 144 | + |
| 145 | + |
| 146 | +\subsubsection{Security} |
| 147 | + |
| 148 | +Unlike some other popen functions, this implementation will never call |
| 149 | +/bin/sh implicitly. This means that all characters, including shell |
| 150 | +metacharacters, can safely be passed to child processes. |
| 151 | + |
| 152 | + |
| 153 | +\subsection{Popen Objects} |
| 154 | + |
| 155 | +Instances of the \class{Popen} class have the following methods: |
| 156 | + |
| 157 | +\begin{methoddesc}{poll}{} |
| 158 | +Check if child process has terminated. Returns returncode |
| 159 | +attribute. |
| 160 | +\end{methoddesc} |
| 161 | + |
| 162 | +\begin{methoddesc}{wait}{} |
| 163 | +Wait for child process to terminate. Returns returncode attribute. |
| 164 | +\end{methoddesc} |
| 165 | + |
| 166 | +\begin{methoddesc}{communicate}{input=None} |
| 167 | +Interact with process: Send data to stdin. Read data from stdout and |
| 168 | +stderr, until end-of-file is reached. Wait for process to terminate. |
| 169 | +The optional \var{stdin} argument should be a string to be sent to the |
| 170 | +child process, or \code{None}, if no data should be sent to the child. |
| 171 | + |
| 172 | +communicate() returns a tuple (stdout, stderr). |
| 173 | + |
| 174 | +\note{The data read is buffered in memory, so do not use this method |
| 175 | +if the data size is large or unlimited.} |
| 176 | +\end{methoddesc} |
| 177 | + |
| 178 | +The following attributes are also available: |
| 179 | + |
| 180 | +\begin{memberdesc}{stdin} |
| 181 | +If the \var{stdin} argument is \code{PIPE}, this attribute is a file |
| 182 | +object that provides input to the child process. Otherwise, it is |
| 183 | +\code{None}. |
| 184 | +\end{memberdesc} |
| 185 | + |
| 186 | +\begin{memberdesc}{stdout} |
| 187 | +If the \var{stdout} argument is \code{PIPE}, this attribute is a file |
| 188 | +object that provides output from the child process. Otherwise, it is |
| 189 | +\code{None}. |
| 190 | +\end{memberdesc} |
| 191 | + |
| 192 | +\begin{memberdesc}{stderr} |
| 193 | +If the \var{stderr} argument is \code{PIPE}, this attribute is file |
| 194 | +object that provides error output from the child process. Otherwise, |
| 195 | +it is \code{None}. |
| 196 | +\end{memberdesc} |
| 197 | + |
| 198 | +\begin{memberdesc}{pid} |
| 199 | +The process ID of the child process. |
| 200 | +\end{memberdesc} |
| 201 | + |
| 202 | +\begin{memberdesc}{returncode} |
| 203 | +The child return code. A \code{None} value indicates that the process |
| 204 | +hasn't terminated yet. A negative value -N indicates that the child |
| 205 | +was terminated by signal N (\UNIX{} only). |
| 206 | +\end{memberdesc} |
| 207 | + |
| 208 | + |
| 209 | +\subsection{Replacing Older Functions with the subprocess Module} |
| 210 | + |
| 211 | +In this section, "a ==> b" means that b can be used as a replacement |
| 212 | +for a. |
| 213 | + |
| 214 | +\note{All functions in this section fail (more or less) silently if |
| 215 | +the executed program cannot be found; this module raises an |
| 216 | +\exception{OSError} exception.} |
| 217 | + |
| 218 | +In the following examples, we assume that the subprocess module is |
| 219 | +imported with "from subprocess import *". |
| 220 | + |
| 221 | +\subsubsection{Replacing /bin/sh shell backquote} |
| 222 | + |
| 223 | +\begin{verbatim} |
| 224 | +output=`mycmd myarg` |
| 225 | +==> |
| 226 | +output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] |
| 227 | +\end{verbatim} |
| 228 | + |
| 229 | +\subsubsection{Replacing shell pipe line} |
| 230 | + |
| 231 | +\begin{verbatim} |
| 232 | +output=`dmesg | grep hda` |
| 233 | +==> |
| 234 | +p1 = Popen(["dmesg"], stdout=PIPE) |
| 235 | +p2 = Popen(["grep", "hda"], stdin=p1.stdout) |
| 236 | +output = p2.communicate()[0] |
| 237 | +\end{verbatim} |
| 238 | + |
| 239 | +\subsubsection{Replacing os.system()} |
| 240 | + |
| 241 | +\begin{verbatim} |
| 242 | +sts = os.system("mycmd" + " myarg") |
| 243 | +==> |
| 244 | +p = Popen("mycmd" + " myarg", shell=True) |
| 245 | +sts = os.waitpid(p.pid, 0) |
| 246 | +\end{verbatim} |
| 247 | + |
| 248 | +Notes: |
| 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 | + |
| 256 | +A more realistic example would look like this: |
| 257 | + |
| 258 | +\begin{verbatim} |
| 259 | +try: |
| 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 |
| 265 | +except OSError, e: |
| 266 | + print >>sys.stderr, "Execution failed:", e |
| 267 | +\end{verbatim} |
| 268 | + |
| 269 | +\subsubsection{Replacing os.spawn*} |
| 270 | + |
| 271 | +P_NOWAIT example: |
| 272 | + |
| 273 | +\begin{verbatim} |
| 274 | +pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") |
| 275 | +==> |
| 276 | +pid = Popen(["/bin/mycmd", "myarg"]).pid |
| 277 | +\end{verbatim} |
| 278 | + |
| 279 | +P_WAIT example: |
| 280 | + |
| 281 | +\begin{verbatim} |
| 282 | +retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg") |
| 283 | +==> |
| 284 | +retcode = call(["/bin/mycmd", "myarg"]) |
| 285 | +\end{verbatim} |
| 286 | + |
| 287 | +Vector example: |
| 288 | + |
| 289 | +\begin{verbatim} |
| 290 | +os.spawnvp(os.P_NOWAIT, path, args) |
| 291 | +==> |
| 292 | +Popen([path] + args[1:]) |
| 293 | +\end{verbatim} |
| 294 | + |
| 295 | +Environment example: |
| 296 | + |
| 297 | +\begin{verbatim} |
| 298 | +os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env) |
| 299 | +==> |
| 300 | +Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}) |
| 301 | +\end{verbatim} |
| 302 | + |
| 303 | +\subsubsection{Replacing os.popen*} |
| 304 | + |
| 305 | +\begin{verbatim} |
| 306 | +pipe = os.popen(cmd, mode='r', bufsize) |
| 307 | +==> |
| 308 | +pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout |
| 309 | +\end{verbatim} |
| 310 | + |
| 311 | +\begin{verbatim} |
| 312 | +pipe = os.popen(cmd, mode='w', bufsize) |
| 313 | +==> |
| 314 | +pipe = 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 | +==> |
| 320 | +p = 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 | +==> |
| 330 | +p = 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 | +==> |
| 340 | +p = 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 |
| 348 | +is executed through /bin/sh. If it is a list, the command is directly |
| 349 | +executed.} |
| 350 | + |
| 351 | +\begin{verbatim} |
| 352 | +(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode) |
| 353 | +==> |
| 354 | +p = 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 | +==> |
| 362 | +p = 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 | + |
| 367 | +The popen2.Popen3 and popen3.Popen4 basically works as subprocess.Popen, |
| 368 | +except 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} |
0 commit comments