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 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 175 | Check if child process has terminated. Set and return :attr:`returncode` |
| 176 | attribute. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 177 | |
| 178 | |
| 179 | .. method:: Popen.wait() |
| 180 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 181 | Wait for child process to terminate. Set and return :attr:`returncode` |
| 182 | attribute. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 183 | |
| 184 | |
| 185 | .. method:: Popen.communicate(input=None) |
| 186 | |
| 187 | Interact with process: Send data to stdin. Read data from stdout and stderr, |
| 188 | until end-of-file is reached. Wait for process to terminate. The optional |
| 189 | *input* argument should be a string to be sent to the child process, or |
| 190 | ``None``, if no data should be sent to the child. |
| 191 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 192 | :meth:`communicate` returns a tuple ``(stdout, stderr)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 193 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 194 | Note that if you want to send data to the process's stdin, you need to create |
| 195 | the Popen object with ``stdin=PIPE``. Similarly, to get anything other than |
| 196 | ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or |
| 197 | ``stderr=PIPE`` too. |
| 198 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 199 | .. note:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 200 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 201 | The data read is buffered in memory, so do not use this method if the data |
| 202 | size is large or unlimited. |
| 203 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 204 | |
| 205 | The following attributes are also available: |
| 206 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 207 | .. attribute:: Popen.stdin |
| 208 | |
| 209 | If the *stdin* argument is ``PIPE``, this attribute is a file object that |
| 210 | provides input to the child process. Otherwise, it is ``None``. |
| 211 | |
| 212 | |
| 213 | .. attribute:: Popen.stdout |
| 214 | |
| 215 | If the *stdout* argument is ``PIPE``, this attribute is a file object that |
| 216 | provides output from the child process. Otherwise, it is ``None``. |
| 217 | |
| 218 | |
| 219 | .. attribute:: Popen.stderr |
| 220 | |
| 221 | If the *stderr* argument is ``PIPE``, this attribute is file object that |
| 222 | provides error output from the child process. Otherwise, it is ``None``. |
| 223 | |
| 224 | |
| 225 | .. attribute:: Popen.pid |
| 226 | |
| 227 | The process ID of the child process. |
| 228 | |
| 229 | |
| 230 | .. attribute:: Popen.returncode |
| 231 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 232 | The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly |
| 233 | by :meth:`communicate`). A ``None`` value indicates that the process |
| 234 | hasn't terminated yet. |
| 235 | |
| 236 | A negative value ``-N`` indicates that the child was terminated by signal |
| 237 | ``N`` (Unix only). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 238 | |
| 239 | |
| 240 | Replacing Older Functions with the subprocess Module |
| 241 | ---------------------------------------------------- |
| 242 | |
| 243 | In this section, "a ==> b" means that b can be used as a replacement for a. |
| 244 | |
| 245 | .. note:: |
| 246 | |
| 247 | All functions in this section fail (more or less) silently if the executed |
| 248 | program cannot be found; this module raises an :exc:`OSError` exception. |
| 249 | |
| 250 | In the following examples, we assume that the subprocess module is imported with |
| 251 | "from subprocess import \*". |
| 252 | |
| 253 | |
| 254 | Replacing /bin/sh shell backquote |
| 255 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 256 | |
| 257 | :: |
| 258 | |
| 259 | output=`mycmd myarg` |
| 260 | ==> |
| 261 | output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] |
| 262 | |
| 263 | |
| 264 | Replacing shell pipe line |
| 265 | ^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 266 | |
| 267 | :: |
| 268 | |
| 269 | output=`dmesg | grep hda` |
| 270 | ==> |
| 271 | p1 = Popen(["dmesg"], stdout=PIPE) |
| 272 | p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) |
| 273 | output = p2.communicate()[0] |
| 274 | |
| 275 | |
| 276 | Replacing os.system() |
| 277 | ^^^^^^^^^^^^^^^^^^^^^ |
| 278 | |
| 279 | :: |
| 280 | |
| 281 | sts = os.system("mycmd" + " myarg") |
| 282 | ==> |
| 283 | p = Popen("mycmd" + " myarg", shell=True) |
| 284 | sts = os.waitpid(p.pid, 0) |
| 285 | |
| 286 | Notes: |
| 287 | |
| 288 | * Calling the program through the shell is usually not required. |
| 289 | |
| 290 | * It's easier to look at the :attr:`returncode` attribute than the exit status. |
| 291 | |
| 292 | A more realistic example would look like this:: |
| 293 | |
| 294 | try: |
| 295 | retcode = call("mycmd" + " myarg", shell=True) |
| 296 | if retcode < 0: |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 297 | print("Child was terminated by signal", -retcode, file=sys.stderr) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 298 | else: |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 299 | print("Child returned", retcode, file=sys.stderr) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 300 | except OSError as e: |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 301 | print("Execution failed:", e, file=sys.stderr) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 302 | |
| 303 | |
| 304 | Replacing os.spawn\* |
| 305 | ^^^^^^^^^^^^^^^^^^^^ |
| 306 | |
| 307 | P_NOWAIT example:: |
| 308 | |
| 309 | pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") |
| 310 | ==> |
| 311 | pid = Popen(["/bin/mycmd", "myarg"]).pid |
| 312 | |
| 313 | P_WAIT example:: |
| 314 | |
| 315 | retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg") |
| 316 | ==> |
| 317 | retcode = call(["/bin/mycmd", "myarg"]) |
| 318 | |
| 319 | Vector example:: |
| 320 | |
| 321 | os.spawnvp(os.P_NOWAIT, path, args) |
| 322 | ==> |
| 323 | Popen([path] + args[1:]) |
| 324 | |
| 325 | Environment example:: |
| 326 | |
| 327 | os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env) |
| 328 | ==> |
| 329 | Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}) |
| 330 | |
| 331 | |
| 332 | Replacing os.popen\* |
| 333 | ^^^^^^^^^^^^^^^^^^^^ |
| 334 | |
| 335 | :: |
| 336 | |
| 337 | pipe = os.popen(cmd, mode='r', bufsize) |
| 338 | ==> |
| 339 | pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout |
| 340 | |
| 341 | :: |
| 342 | |
| 343 | pipe = os.popen(cmd, mode='w', bufsize) |
| 344 | ==> |
| 345 | pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin |
| 346 | |