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* |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 17 | |
| 18 | Information about how the :mod:`subprocess` module can be used to replace these |
| 19 | modules and functions can be found in the following sections. |
| 20 | |
| 21 | |
| 22 | Using the subprocess Module |
| 23 | --------------------------- |
| 24 | |
| 25 | This module defines one class called :class:`Popen`: |
| 26 | |
| 27 | |
| 28 | .. 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) |
| 29 | |
| 30 | Arguments are: |
| 31 | |
| 32 | *args* should be a string, or a sequence of program arguments. The program to |
| 33 | execute is normally the first item in the args sequence or string, but can be |
| 34 | explicitly set by using the executable argument. |
| 35 | |
| 36 | On Unix, with *shell=False* (default): In this case, the Popen class uses |
| 37 | :meth:`os.execvp` to execute the child program. *args* should normally be a |
| 38 | sequence. A string will be treated as a sequence with the string as the only |
| 39 | item (the program to execute). |
| 40 | |
| 41 | On Unix, with *shell=True*: If args is a string, it specifies the command string |
| 42 | to execute through the shell. If *args* is a sequence, the first item specifies |
| 43 | the command string, and any additional items will be treated as additional shell |
| 44 | arguments. |
| 45 | |
| 46 | On Windows: the :class:`Popen` class uses CreateProcess() to execute the child |
| 47 | program, which operates on strings. If *args* is a sequence, it will be |
| 48 | converted to a string using the :meth:`list2cmdline` method. Please note that |
| 49 | not all MS Windows applications interpret the command line the same way: |
| 50 | :meth:`list2cmdline` is designed for applications using the same rules as the MS |
| 51 | C runtime. |
| 52 | |
| 53 | *bufsize*, if given, has the same meaning as the corresponding argument to the |
| 54 | built-in open() function: :const:`0` means unbuffered, :const:`1` means line |
| 55 | buffered, any other positive value means use a buffer of (approximately) that |
| 56 | size. A negative *bufsize* means to use the system default, which usually means |
| 57 | fully buffered. The default value for *bufsize* is :const:`0` (unbuffered). |
| 58 | |
| 59 | The *executable* argument specifies the program to execute. It is very seldom |
| 60 | needed: Usually, the program to execute is defined by the *args* argument. If |
| 61 | ``shell=True``, the *executable* argument specifies which shell to use. On Unix, |
| 62 | the default shell is :file:`/bin/sh`. On Windows, the default shell is |
| 63 | specified by the :envvar:`COMSPEC` environment variable. |
| 64 | |
| 65 | *stdin*, *stdout* and *stderr* specify the executed programs' standard input, |
| 66 | standard output and standard error file handles, respectively. Valid values are |
| 67 | ``PIPE``, an existing file descriptor (a positive integer), an existing file |
| 68 | object, and ``None``. ``PIPE`` indicates that a new pipe to the child should be |
| 69 | created. With ``None``, no redirection will occur; the child's file handles |
| 70 | will be inherited from the parent. Additionally, *stderr* can be ``STDOUT``, |
| 71 | which indicates that the stderr data from the applications should be captured |
| 72 | into the same file handle as for stdout. |
| 73 | |
| 74 | If *preexec_fn* is set to a callable object, this object will be called in the |
| 75 | child process just before the child is executed. (Unix only) |
| 76 | |
| 77 | If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and |
| 78 | :const:`2` will be closed before the child process is executed. (Unix only). |
| 79 | Or, on Windows, if *close_fds* is true then no handles will be inherited by the |
| 80 | child process. Note that on Windows, you cannot set *close_fds* to true and |
| 81 | also redirect the standard handles by setting *stdin*, *stdout* or *stderr*. |
| 82 | |
| 83 | If *shell* is :const:`True`, the specified command will be executed through the |
| 84 | shell. |
| 85 | |
| 86 | If *cwd* is not ``None``, the child's current directory will be changed to *cwd* |
| 87 | before it is executed. Note that this directory is not considered when |
| 88 | searching the executable, so you can't specify the program's path relative to |
| 89 | *cwd*. |
| 90 | |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 91 | If *env* is not ``None``, it must be a mapping that defines the environment |
| 92 | variables for the new process; these are used instead of inheriting the current |
| 93 | process' environment, which is the default behavior. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 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 | |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame^] | 115 | This module also defines four shortcut functions: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 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 | |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame^] | 140 | .. function:: getstatusoutput(cmd) |
| 141 | Return ``(status, output)`` of executing *cmd* in a shell. |
| 142 | |
| 143 | Execute the string *cmd* in a shell with :func:`os.popen` and return a 2-tuple |
| 144 | ``(status, output)``. *cmd* is actually run as ``{ cmd ; } 2>&1``, so that the |
| 145 | returned output will contain output or error messages. A trailing newline is |
| 146 | stripped from the output. The exit status for the command can be interpreted |
| 147 | according to the rules for the C function :cfunc:`wait`. Example:: |
| 148 | |
| 149 | >>> import subprocess |
| 150 | >>> subprocess.getstatusoutput('ls /bin/ls') |
| 151 | (0, '/bin/ls') |
| 152 | >>> subprocess.getstatusoutput('cat /bin/junk') |
| 153 | (256, 'cat: /bin/junk: No such file or directory') |
| 154 | >>> subprocess.getstatusoutput('/bin/junk') |
| 155 | (256, 'sh: /bin/junk: not found') |
| 156 | |
| 157 | |
| 158 | .. function:: getoutput(cmd) |
| 159 | Return output ``(stdout or stderr)`` of executing *cmd* in a shell. |
| 160 | |
| 161 | Like :func:`getstatusoutput`, except the exit status is ignored and the return |
| 162 | value is a string containing the command's output. Example:: |
| 163 | |
| 164 | >>> import subprocess |
| 165 | >>> subprocess.getoutput('ls /bin/ls') |
| 166 | '/bin/ls' |
| 167 | |
| 168 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 169 | Exceptions |
| 170 | ^^^^^^^^^^ |
| 171 | |
| 172 | Exceptions raised in the child process, before the new program has started to |
| 173 | execute, will be re-raised in the parent. Additionally, the exception object |
| 174 | will have one extra attribute called :attr:`child_traceback`, which is a string |
| 175 | containing traceback information from the childs point of view. |
| 176 | |
| 177 | The most common exception raised is :exc:`OSError`. This occurs, for example, |
| 178 | when trying to execute a non-existent file. Applications should prepare for |
| 179 | :exc:`OSError` exceptions. |
| 180 | |
| 181 | A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid |
| 182 | arguments. |
| 183 | |
| 184 | check_call() will raise :exc:`CalledProcessError`, if the called process returns |
| 185 | a non-zero return code. |
| 186 | |
| 187 | |
| 188 | Security |
| 189 | ^^^^^^^^ |
| 190 | |
| 191 | Unlike some other popen functions, this implementation will never call /bin/sh |
| 192 | implicitly. This means that all characters, including shell metacharacters, can |
| 193 | safely be passed to child processes. |
| 194 | |
| 195 | |
| 196 | Popen Objects |
| 197 | ------------- |
| 198 | |
| 199 | Instances of the :class:`Popen` class have the following methods: |
| 200 | |
| 201 | |
| 202 | .. method:: Popen.poll() |
| 203 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 204 | Check if child process has terminated. Set and return :attr:`returncode` |
| 205 | attribute. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 206 | |
| 207 | |
| 208 | .. method:: Popen.wait() |
| 209 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 210 | Wait for child process to terminate. Set and return :attr:`returncode` |
| 211 | attribute. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 212 | |
| 213 | |
| 214 | .. method:: Popen.communicate(input=None) |
| 215 | |
| 216 | Interact with process: Send data to stdin. Read data from stdout and stderr, |
| 217 | until end-of-file is reached. Wait for process to terminate. The optional |
| 218 | *input* argument should be a string to be sent to the child process, or |
| 219 | ``None``, if no data should be sent to the child. |
| 220 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 221 | :meth:`communicate` returns a tuple ``(stdout, stderr)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 222 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 223 | Note that if you want to send data to the process's stdin, you need to create |
| 224 | the Popen object with ``stdin=PIPE``. Similarly, to get anything other than |
| 225 | ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or |
| 226 | ``stderr=PIPE`` too. |
| 227 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 228 | .. note:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 229 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 230 | The data read is buffered in memory, so do not use this method if the data |
| 231 | size is large or unlimited. |
| 232 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 233 | |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 234 | .. method:: Popen.send_signal(signal) |
| 235 | |
| 236 | Sends the signal *signal* to the child. |
| 237 | |
| 238 | .. note:: |
| 239 | |
| 240 | On Windows only SIGTERM is supported so far. It's an alias for |
| 241 | :meth:`terminate`. |
| 242 | |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 243 | |
| 244 | .. method:: Popen.terminate() |
| 245 | |
| 246 | Stop the child. On Posix OSs the method sends SIGTERM to the |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 247 | child. On Windows the Win32 API function :cfunc:`TerminateProcess` is called |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 248 | to stop the child. |
| 249 | |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 250 | |
| 251 | .. method:: Popen.kill() |
| 252 | |
| 253 | Kills the child. On Posix OSs the function sends SIGKILL to the child. |
| 254 | On Windows :meth:`kill` is an alias for :meth:`terminate`. |
| 255 | |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 256 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 257 | The following attributes are also available: |
| 258 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 259 | .. attribute:: Popen.stdin |
| 260 | |
| 261 | If the *stdin* argument is ``PIPE``, this attribute is a file object that |
| 262 | provides input to the child process. Otherwise, it is ``None``. |
| 263 | |
| 264 | |
| 265 | .. attribute:: Popen.stdout |
| 266 | |
| 267 | If the *stdout* argument is ``PIPE``, this attribute is a file object that |
| 268 | provides output from the child process. Otherwise, it is ``None``. |
| 269 | |
| 270 | |
| 271 | .. attribute:: Popen.stderr |
| 272 | |
| 273 | If the *stderr* argument is ``PIPE``, this attribute is file object that |
| 274 | provides error output from the child process. Otherwise, it is ``None``. |
| 275 | |
| 276 | |
| 277 | .. attribute:: Popen.pid |
| 278 | |
| 279 | The process ID of the child process. |
| 280 | |
| 281 | |
| 282 | .. attribute:: Popen.returncode |
| 283 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 284 | The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly |
| 285 | by :meth:`communicate`). A ``None`` value indicates that the process |
| 286 | hasn't terminated yet. |
| 287 | |
| 288 | A negative value ``-N`` indicates that the child was terminated by signal |
| 289 | ``N`` (Unix only). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 290 | |
| 291 | |
| 292 | Replacing Older Functions with the subprocess Module |
| 293 | ---------------------------------------------------- |
| 294 | |
| 295 | In this section, "a ==> b" means that b can be used as a replacement for a. |
| 296 | |
| 297 | .. note:: |
| 298 | |
| 299 | All functions in this section fail (more or less) silently if the executed |
| 300 | program cannot be found; this module raises an :exc:`OSError` exception. |
| 301 | |
| 302 | In the following examples, we assume that the subprocess module is imported with |
| 303 | "from subprocess import \*". |
| 304 | |
| 305 | |
| 306 | Replacing /bin/sh shell backquote |
| 307 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 308 | |
| 309 | :: |
| 310 | |
| 311 | output=`mycmd myarg` |
| 312 | ==> |
| 313 | output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] |
| 314 | |
| 315 | |
| 316 | Replacing shell pipe line |
| 317 | ^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 318 | |
| 319 | :: |
| 320 | |
| 321 | output=`dmesg | grep hda` |
| 322 | ==> |
| 323 | p1 = Popen(["dmesg"], stdout=PIPE) |
| 324 | p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) |
| 325 | output = p2.communicate()[0] |
| 326 | |
| 327 | |
| 328 | Replacing os.system() |
| 329 | ^^^^^^^^^^^^^^^^^^^^^ |
| 330 | |
| 331 | :: |
| 332 | |
| 333 | sts = os.system("mycmd" + " myarg") |
| 334 | ==> |
| 335 | p = Popen("mycmd" + " myarg", shell=True) |
| 336 | sts = os.waitpid(p.pid, 0) |
| 337 | |
| 338 | Notes: |
| 339 | |
| 340 | * Calling the program through the shell is usually not required. |
| 341 | |
| 342 | * It's easier to look at the :attr:`returncode` attribute than the exit status. |
| 343 | |
| 344 | A more realistic example would look like this:: |
| 345 | |
| 346 | try: |
| 347 | retcode = call("mycmd" + " myarg", shell=True) |
| 348 | if retcode < 0: |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 349 | print("Child was terminated by signal", -retcode, file=sys.stderr) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 350 | else: |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 351 | print("Child returned", retcode, file=sys.stderr) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 352 | except OSError as e: |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 353 | print("Execution failed:", e, file=sys.stderr) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 354 | |
| 355 | |
| 356 | Replacing os.spawn\* |
| 357 | ^^^^^^^^^^^^^^^^^^^^ |
| 358 | |
| 359 | P_NOWAIT example:: |
| 360 | |
| 361 | pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") |
| 362 | ==> |
| 363 | pid = Popen(["/bin/mycmd", "myarg"]).pid |
| 364 | |
| 365 | P_WAIT example:: |
| 366 | |
| 367 | retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg") |
| 368 | ==> |
| 369 | retcode = call(["/bin/mycmd", "myarg"]) |
| 370 | |
| 371 | Vector example:: |
| 372 | |
| 373 | os.spawnvp(os.P_NOWAIT, path, args) |
| 374 | ==> |
| 375 | Popen([path] + args[1:]) |
| 376 | |
| 377 | Environment example:: |
| 378 | |
| 379 | os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env) |
| 380 | ==> |
| 381 | Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}) |
| 382 | |
| 383 | |
| 384 | Replacing os.popen\* |
| 385 | ^^^^^^^^^^^^^^^^^^^^ |
| 386 | |
| 387 | :: |
| 388 | |
| 389 | pipe = os.popen(cmd, mode='r', bufsize) |
| 390 | ==> |
| 391 | pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout |
| 392 | |
| 393 | :: |
| 394 | |
| 395 | pipe = os.popen(cmd, mode='w', bufsize) |
| 396 | ==> |
| 397 | pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin |
| 398 | |