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