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 | |
Fredrik Lundh | b04b6af | 2004-10-17 16:29:48 +0000 | [diff] [blame] | 15 | \begin{verbatim} |
| 16 | os.system |
| 17 | os.spawn* |
Fredrik Lundh | b04b6af | 2004-10-17 16:29:48 +0000 | [diff] [blame] | 18 | commands.* |
| 19 | \end{verbatim} |
| 20 | |
| 21 | Information about how the \module{subprocess} module can be used to |
| 22 | replace these modules and functions can be found in the following |
| 23 | sections. |
| 24 | |
| 25 | \subsection{Using the subprocess Module} |
| 26 | |
| 27 | This 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 | |
| 35 | Arguments are: |
| 36 | |
| 37 | \var{args} should be a string, or a sequence of program arguments. The |
| 38 | program to execute is normally the first item in the args sequence or |
| 39 | string, but can be explicitly set by using the executable argument. |
| 40 | |
| 41 | On \UNIX{}, with \var{shell=False} (default): In this case, the Popen |
| 42 | class uses \method{os.execvp()} to execute the child program. |
| 43 | \var{args} should normally be a sequence. A string will be treated as a |
| 44 | sequence with the string as the only item (the program to execute). |
| 45 | |
| 46 | On \UNIX{}, with \var{shell=True}: If args is a string, it specifies the |
| 47 | command string to execute through the shell. If \var{args} is a |
| 48 | sequence, the first item specifies the command string, and any |
| 49 | additional items will be treated as additional shell arguments. |
| 50 | |
| 51 | On Windows: the \class{Popen} class uses CreateProcess() to execute |
| 52 | the child program, which operates on strings. If \var{args} is a |
| 53 | sequence, it will be converted to a string using the |
| 54 | \method{list2cmdline} method. Please note that not all MS Windows |
| 55 | applications interpret the command line the same way: |
| 56 | \method{list2cmdline} is designed for applications using the same |
| 57 | rules as the MS C runtime. |
| 58 | |
| 59 | \var{bufsize}, if given, has the same meaning as the corresponding |
| 60 | argument to the built-in open() function: \constant{0} means unbuffered, |
| 61 | \constant{1} means line buffered, any other positive value means use a |
| 62 | buffer of (approximately) that size. A negative \var{bufsize} means to |
| 63 | use the system default, which usually means fully buffered. The default |
| 64 | value for \var{bufsize} is \constant{0} (unbuffered). |
| 65 | |
Peter Astrand | 3546188 | 2004-11-07 16:38:08 +0000 | [diff] [blame] | 66 | The \var{executable} argument specifies the program to execute. It is |
| 67 | very seldom needed: Usually, the program to execute is defined by the |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 68 | \var{args} argument. If \code{shell=True}, the \var{executable} |
Peter Astrand | 3546188 | 2004-11-07 16:38:08 +0000 | [diff] [blame] | 69 | argument specifies which shell to use. On \UNIX{}, the default shell |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 70 | is \file{/bin/sh}. On Windows, the default shell is specified by the |
| 71 | \envvar{COMSPEC} environment variable. |
Peter Astrand | 3546188 | 2004-11-07 16:38:08 +0000 | [diff] [blame] | 72 | |
Fredrik Lundh | b04b6af | 2004-10-17 16:29:48 +0000 | [diff] [blame] | 73 | \var{stdin}, \var{stdout} and \var{stderr} specify the executed |
| 74 | programs' standard input, standard output and standard error file |
| 75 | handles, respectively. Valid values are \code{PIPE}, an existing file |
| 76 | descriptor (a positive integer), an existing file object, and |
| 77 | \code{None}. \code{PIPE} indicates that a new pipe to the child |
| 78 | should be created. With \code{None}, no redirection will occur; the |
| 79 | child's file handles will be inherited from the parent. Additionally, |
| 80 | \var{stderr} can be \code{STDOUT}, which indicates that the stderr |
| 81 | data from the applications should be captured into the same file |
| 82 | handle as for stdout. |
| 83 | |
| 84 | If \var{preexec_fn} is set to a callable object, this object will be |
| 85 | called in the child process just before the child is executed. |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 86 | (\UNIX{} only) |
Fredrik Lundh | b04b6af | 2004-10-17 16:29:48 +0000 | [diff] [blame] | 87 | |
| 88 | If \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 Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 90 | executed. (\UNIX{} only) |
Fredrik Lundh | b04b6af | 2004-10-17 16:29:48 +0000 | [diff] [blame] | 91 | |
| 92 | If \var{shell} is \constant{True}, the specified command will be |
| 93 | executed through the shell. |
| 94 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 95 | If \var{cwd} is not \code{None}, the child's current directory will be |
| 96 | changed to \var{cwd} before it is executed. Note that this directory |
| 97 | is not considered when searching the executable, so you can't specify |
| 98 | the program's path relative to \var{cwd}. |
Fredrik Lundh | b04b6af | 2004-10-17 16:29:48 +0000 | [diff] [blame] | 99 | |
| 100 | If \var{env} is not \code{None}, it defines the environment variables |
| 101 | for the new process. |
| 102 | |
| 103 | If \var{universal_newlines} is \constant{True}, the file objects stdout |
Georg Brandl | 0f19423 | 2006-01-01 21:35:20 +0000 | [diff] [blame] | 104 | and stderr are opened as text files, but lines may be terminated by |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 105 | any of \code{'\e n'}, the \UNIX{} end-of-line convention, \code{'\e r'}, |
Fredrik Lundh | b04b6af | 2004-10-17 16:29:48 +0000 | [diff] [blame] | 106 | the Macintosh convention or \code{'\e r\e n'}, the Windows convention. |
| 107 | All of these external representations are seen as \code{'\e n'} by the |
| 108 | Python program. \note{This feature is only available if Python is built |
| 109 | with universal newline support (the default). Also, the newlines |
| 110 | attribute of the file objects \member{stdout}, \member{stdin} and |
| 111 | \member{stderr} are not updated by the communicate() method.} |
| 112 | |
| 113 | The \var{startupinfo} and \var{creationflags}, if given, will be |
| 114 | passed to the underlying CreateProcess() function. They can specify |
| 115 | things such as appearance of the main window and priority for the new |
| 116 | process. (Windows only) |
| 117 | \end{classdesc} |
| 118 | |
| 119 | \subsubsection{Convenience Functions} |
| 120 | |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 121 | This module also defines two shortcut functions: |
Fredrik Lundh | b04b6af | 2004-10-17 16:29:48 +0000 | [diff] [blame] | 122 | |
Peter Astrand | 5f5e141 | 2004-12-05 20:15:36 +0000 | [diff] [blame] | 123 | \begin{funcdesc}{call}{*popenargs, **kwargs} |
Fredrik Lundh | b04b6af | 2004-10-17 16:29:48 +0000 | [diff] [blame] | 124 | Run command with arguments. Wait for command to complete, then |
| 125 | return the \member{returncode} attribute. |
| 126 | |
| 127 | The 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 Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 134 | \begin{funcdesc}{check_call}{*popenargs, **kwargs} |
| 135 | Run command with arguments. Wait for command to complete. If the exit |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 136 | code was zero then return, otherwise raise \exception{CalledProcessError.} |
| 137 | The \exception{CalledProcessError} object will have the return code in the |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 138 | \member{returncode} attribute. |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 139 | |
| 140 | The 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 Lundh | b04b6af | 2004-10-17 16:29:48 +0000 | [diff] [blame] | 146 | |
| 147 | \subsubsection{Exceptions} |
| 148 | |
| 149 | Exceptions raised in the child process, before the new program has |
| 150 | started to execute, will be re-raised in the parent. Additionally, |
| 151 | the exception object will have one extra attribute called |
| 152 | \member{child_traceback}, which is a string containing traceback |
| 153 | information from the childs point of view. |
| 154 | |
| 155 | The most common exception raised is \exception{OSError}. This occurs, |
| 156 | for example, when trying to execute a non-existent file. Applications |
| 157 | should prepare for \exception{OSError} exceptions. |
| 158 | |
| 159 | A \exception{ValueError} will be raised if \class{Popen} is called |
| 160 | with invalid arguments. |
| 161 | |
Thomas Wouters | 0e3f591 | 2006-08-11 14:57:12 +0000 | [diff] [blame] | 162 | check_call() will raise \exception{CalledProcessError}, if the called |
| 163 | process returns a non-zero return code. |
Peter Astrand | 454f767 | 2005-01-01 09:36:35 +0000 | [diff] [blame] | 164 | |
Fredrik Lundh | b04b6af | 2004-10-17 16:29:48 +0000 | [diff] [blame] | 165 | |
| 166 | \subsubsection{Security} |
| 167 | |
| 168 | Unlike some other popen functions, this implementation will never call |
| 169 | /bin/sh implicitly. This means that all characters, including shell |
| 170 | metacharacters, can safely be passed to child processes. |
| 171 | |
| 172 | |
| 173 | \subsection{Popen Objects} |
| 174 | |
| 175 | Instances of the \class{Popen} class have the following methods: |
| 176 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 177 | \begin{methoddesc}[Popen]{poll}{} |
Fredrik Lundh | b04b6af | 2004-10-17 16:29:48 +0000 | [diff] [blame] | 178 | Check if child process has terminated. Returns returncode |
| 179 | attribute. |
| 180 | \end{methoddesc} |
| 181 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 182 | \begin{methoddesc}[Popen]{wait}{} |
Fredrik Lundh | b04b6af | 2004-10-17 16:29:48 +0000 | [diff] [blame] | 183 | Wait for child process to terminate. Returns returncode attribute. |
| 184 | \end{methoddesc} |
| 185 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 186 | \begin{methoddesc}[Popen]{communicate}{input=None} |
Fredrik Lundh | b04b6af | 2004-10-17 16:29:48 +0000 | [diff] [blame] | 187 | Interact with process: Send data to stdin. Read data from stdout and |
| 188 | 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] | 189 | 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] | 190 | child process, or \code{None}, if no data should be sent to the child. |
| 191 | |
| 192 | communicate() returns a tuple (stdout, stderr). |
| 193 | |
| 194 | \note{The data read is buffered in memory, so do not use this method |
| 195 | if the data size is large or unlimited.} |
| 196 | \end{methoddesc} |
| 197 | |
| 198 | The following attributes are also available: |
| 199 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 200 | \begin{memberdesc}[Popen]{stdin} |
Fredrik Lundh | b04b6af | 2004-10-17 16:29:48 +0000 | [diff] [blame] | 201 | If the \var{stdin} argument is \code{PIPE}, this attribute is a file |
| 202 | object that provides input to the child process. Otherwise, it is |
| 203 | \code{None}. |
| 204 | \end{memberdesc} |
| 205 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 206 | \begin{memberdesc}[Popen]{stdout} |
Fredrik Lundh | b04b6af | 2004-10-17 16:29:48 +0000 | [diff] [blame] | 207 | If the \var{stdout} argument is \code{PIPE}, this attribute is a file |
| 208 | object that provides output from the child process. Otherwise, it is |
| 209 | \code{None}. |
| 210 | \end{memberdesc} |
| 211 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 212 | \begin{memberdesc}[Popen]{stderr} |
Fredrik Lundh | b04b6af | 2004-10-17 16:29:48 +0000 | [diff] [blame] | 213 | If the \var{stderr} argument is \code{PIPE}, this attribute is file |
| 214 | object that provides error output from the child process. Otherwise, |
| 215 | it is \code{None}. |
| 216 | \end{memberdesc} |
| 217 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 218 | \begin{memberdesc}[Popen]{pid} |
Fredrik Lundh | b04b6af | 2004-10-17 16:29:48 +0000 | [diff] [blame] | 219 | The process ID of the child process. |
| 220 | \end{memberdesc} |
| 221 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 222 | \begin{memberdesc}[Popen]{returncode} |
Fredrik Lundh | b04b6af | 2004-10-17 16:29:48 +0000 | [diff] [blame] | 223 | The child return code. A \code{None} value indicates that the process |
| 224 | hasn't terminated yet. A negative value -N indicates that the child |
| 225 | was terminated by signal N (\UNIX{} only). |
| 226 | \end{memberdesc} |
| 227 | |
| 228 | |
| 229 | \subsection{Replacing Older Functions with the subprocess Module} |
| 230 | |
| 231 | In this section, "a ==> b" means that b can be used as a replacement |
| 232 | for a. |
| 233 | |
| 234 | \note{All functions in this section fail (more or less) silently if |
| 235 | the executed program cannot be found; this module raises an |
| 236 | \exception{OSError} exception.} |
| 237 | |
| 238 | In the following examples, we assume that the subprocess module is |
| 239 | imported with "from subprocess import *". |
| 240 | |
| 241 | \subsubsection{Replacing /bin/sh shell backquote} |
| 242 | |
| 243 | \begin{verbatim} |
| 244 | output=`mycmd myarg` |
| 245 | ==> |
| 246 | output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] |
| 247 | \end{verbatim} |
| 248 | |
| 249 | \subsubsection{Replacing shell pipe line} |
| 250 | |
| 251 | \begin{verbatim} |
| 252 | output=`dmesg | grep hda` |
| 253 | ==> |
| 254 | p1 = Popen(["dmesg"], stdout=PIPE) |
Peter Astrand | 6fdf3cb | 2004-11-30 18:06:42 +0000 | [diff] [blame] | 255 | p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) |
Fredrik Lundh | b04b6af | 2004-10-17 16:29:48 +0000 | [diff] [blame] | 256 | output = p2.communicate()[0] |
| 257 | \end{verbatim} |
| 258 | |
| 259 | \subsubsection{Replacing os.system()} |
| 260 | |
| 261 | \begin{verbatim} |
| 262 | sts = os.system("mycmd" + " myarg") |
| 263 | ==> |
| 264 | p = Popen("mycmd" + " myarg", shell=True) |
| 265 | sts = os.waitpid(p.pid, 0) |
| 266 | \end{verbatim} |
| 267 | |
| 268 | Notes: |
| 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 | |
| 276 | A more realistic example would look like this: |
| 277 | |
| 278 | \begin{verbatim} |
| 279 | try: |
| 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 Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 285 | except OSError as e: |
Fredrik Lundh | b04b6af | 2004-10-17 16:29:48 +0000 | [diff] [blame] | 286 | print >>sys.stderr, "Execution failed:", e |
| 287 | \end{verbatim} |
| 288 | |
| 289 | \subsubsection{Replacing os.spawn*} |
| 290 | |
| 291 | P_NOWAIT example: |
| 292 | |
| 293 | \begin{verbatim} |
| 294 | pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") |
| 295 | ==> |
| 296 | pid = Popen(["/bin/mycmd", "myarg"]).pid |
| 297 | \end{verbatim} |
| 298 | |
| 299 | P_WAIT example: |
| 300 | |
| 301 | \begin{verbatim} |
| 302 | retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg") |
| 303 | ==> |
| 304 | retcode = call(["/bin/mycmd", "myarg"]) |
| 305 | \end{verbatim} |
| 306 | |
| 307 | Vector example: |
| 308 | |
| 309 | \begin{verbatim} |
| 310 | os.spawnvp(os.P_NOWAIT, path, args) |
| 311 | ==> |
| 312 | Popen([path] + args[1:]) |
| 313 | \end{verbatim} |
| 314 | |
| 315 | Environment example: |
| 316 | |
| 317 | \begin{verbatim} |
| 318 | os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env) |
| 319 | ==> |
| 320 | Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}) |
| 321 | \end{verbatim} |
| 322 | |
| 323 | \subsubsection{Replacing os.popen*} |
| 324 | |
| 325 | \begin{verbatim} |
| 326 | pipe = os.popen(cmd, mode='r', bufsize) |
| 327 | ==> |
| 328 | pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout |
| 329 | \end{verbatim} |
| 330 | |
| 331 | \begin{verbatim} |
| 332 | pipe = os.popen(cmd, mode='w', bufsize) |
| 333 | ==> |
| 334 | pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin |
| 335 | \end{verbatim} |