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