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 | |
Benjamin Peterson | 4118174 | 2008-07-02 20:22:54 +0000 | [diff] [blame] | 21 | .. seealso:: |
| 22 | |
| 23 | :pep:`324` -- PEP proposing the subprocess module |
| 24 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 25 | |
| 26 | Using the subprocess Module |
| 27 | --------------------------- |
| 28 | |
| 29 | This module defines one class called :class:`Popen`: |
| 30 | |
| 31 | |
| 32 | .. 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) |
| 33 | |
| 34 | Arguments are: |
| 35 | |
Benjamin Peterson | d18de0e | 2008-07-31 20:21:46 +0000 | [diff] [blame] | 36 | *args* should be a string, or a sequence of program arguments. The program |
Benjamin Peterson | fa0d703 | 2009-06-01 22:42:33 +0000 | [diff] [blame] | 37 | to execute is normally the first item in the args sequence or the string if |
| 38 | a string is given, but can be explicitly set by using the *executable* |
| 39 | argument. When *executable* is given, the first item in the args sequence |
| 40 | is still treated by most programs as the command name, which can then be |
| 41 | different from the actual executable name. On Unix, it becomes the display |
| 42 | name for the executing program in utilities such as :program:`ps`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 43 | |
| 44 | On Unix, with *shell=False* (default): In this case, the Popen class uses |
| 45 | :meth:`os.execvp` to execute the child program. *args* should normally be a |
| 46 | sequence. A string will be treated as a sequence with the string as the only |
| 47 | item (the program to execute). |
| 48 | |
| 49 | On Unix, with *shell=True*: If args is a string, it specifies the command string |
| 50 | to execute through the shell. If *args* is a sequence, the first item specifies |
| 51 | the command string, and any additional items will be treated as additional shell |
| 52 | arguments. |
| 53 | |
| 54 | On Windows: the :class:`Popen` class uses CreateProcess() to execute the child |
| 55 | program, which operates on strings. If *args* is a sequence, it will be |
| 56 | converted to a string using the :meth:`list2cmdline` method. Please note that |
| 57 | not all MS Windows applications interpret the command line the same way: |
| 58 | :meth:`list2cmdline` is designed for applications using the same rules as the MS |
| 59 | C runtime. |
| 60 | |
| 61 | *bufsize*, if given, has the same meaning as the corresponding argument to the |
| 62 | built-in open() function: :const:`0` means unbuffered, :const:`1` means line |
| 63 | buffered, any other positive value means use a buffer of (approximately) that |
| 64 | size. A negative *bufsize* means to use the system default, which usually means |
| 65 | fully buffered. The default value for *bufsize* is :const:`0` (unbuffered). |
| 66 | |
| 67 | The *executable* argument specifies the program to execute. It is very seldom |
| 68 | needed: Usually, the program to execute is defined by the *args* argument. If |
| 69 | ``shell=True``, the *executable* argument specifies which shell to use. On Unix, |
| 70 | the default shell is :file:`/bin/sh`. On Windows, the default shell is |
| 71 | specified by the :envvar:`COMSPEC` environment variable. |
| 72 | |
| 73 | *stdin*, *stdout* and *stderr* specify the executed programs' standard input, |
Georg Brandl | af265f4 | 2008-12-07 15:06:20 +0000 | [diff] [blame] | 74 | standard output and standard error file handles, respectively. Valid values |
| 75 | are :data:`PIPE`, an existing file descriptor (a positive integer), an |
| 76 | existing file object, and ``None``. :data:`PIPE` indicates that a new pipe |
| 77 | to the child should be created. With ``None``, no redirection will occur; |
| 78 | the child's file handles will be inherited from the parent. Additionally, |
| 79 | *stderr* can be :data:`STDOUT`, which indicates that the stderr data from the |
| 80 | applications should be captured into the same file handle as for stdout. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 81 | |
| 82 | If *preexec_fn* is set to a callable object, this object will be called in the |
| 83 | child process just before the child is executed. (Unix only) |
| 84 | |
| 85 | If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and |
| 86 | :const:`2` will be closed before the child process is executed. (Unix only). |
| 87 | Or, on Windows, if *close_fds* is true then no handles will be inherited by the |
| 88 | child process. Note that on Windows, you cannot set *close_fds* to true and |
| 89 | also redirect the standard handles by setting *stdin*, *stdout* or *stderr*. |
| 90 | |
| 91 | If *shell* is :const:`True`, the specified command will be executed through the |
| 92 | shell. |
| 93 | |
| 94 | If *cwd* is not ``None``, the child's current directory will be changed to *cwd* |
| 95 | before it is executed. Note that this directory is not considered when |
| 96 | searching the executable, so you can't specify the program's path relative to |
| 97 | *cwd*. |
| 98 | |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 99 | If *env* is not ``None``, it must be a mapping that defines the environment |
| 100 | variables for the new process; these are used instead of inheriting the current |
| 101 | process' environment, which is the default behavior. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 102 | |
R. David Murray | 1055e89 | 2009-04-16 18:15:32 +0000 | [diff] [blame] | 103 | .. note:: |
R. David Murray | f4ac149 | 2009-04-15 22:35:15 +0000 | [diff] [blame] | 104 | |
R. David Murray | 1055e89 | 2009-04-16 18:15:32 +0000 | [diff] [blame] | 105 | If specified, *env* must provide any variables required |
| 106 | for the program to execute. On Windows, in order to run a |
| 107 | `side-by-side assembly`_ the specified *env* **must** include a valid |
R. David Murray | f4ac149 | 2009-04-15 22:35:15 +0000 | [diff] [blame] | 108 | :envvar:`SystemRoot`. |
| 109 | |
R. David Murray | 1055e89 | 2009-04-16 18:15:32 +0000 | [diff] [blame] | 110 | .. _side-by-side assembly: http://en.wikipedia.org/wiki/Side-by-Side_Assembly |
| 111 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 112 | If *universal_newlines* is :const:`True`, the file objects stdout and stderr are |
| 113 | opened as text files, but lines may be terminated by any of ``'\n'``, the Unix |
Georg Brandl | c575c90 | 2008-09-13 17:46:05 +0000 | [diff] [blame] | 114 | end-of-line convention, ``'\r'``, the old Macintosh convention or ``'\r\n'``, the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 115 | Windows convention. All of these external representations are seen as ``'\n'`` |
| 116 | by the Python program. |
| 117 | |
| 118 | .. note:: |
| 119 | |
| 120 | This feature is only available if Python is built with universal newline support |
| 121 | (the default). Also, the newlines attribute of the file objects :attr:`stdout`, |
Georg Brandl | e11787a | 2008-07-01 19:10:52 +0000 | [diff] [blame] | 122 | :attr:`stdin` and :attr:`stderr` are not updated by the :meth:`communicate` method. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 123 | |
| 124 | The *startupinfo* and *creationflags*, if given, will be passed to the |
| 125 | underlying CreateProcess() function. They can specify things such as appearance |
| 126 | of the main window and priority for the new process. (Windows only) |
| 127 | |
| 128 | |
Georg Brandl | af265f4 | 2008-12-07 15:06:20 +0000 | [diff] [blame] | 129 | .. data:: PIPE |
| 130 | |
| 131 | Special value that can be used as the *stdin*, *stdout* or *stderr* argument |
| 132 | to :class:`Popen` and indicates that a pipe to the standard stream should be |
| 133 | opened. |
| 134 | |
| 135 | |
| 136 | .. data:: STDOUT |
| 137 | |
| 138 | Special value that can be used as the *stderr* argument to :class:`Popen` and |
| 139 | indicates that standard error should go into the same handle as standard |
| 140 | output. |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 141 | |
Georg Brandl | af265f4 | 2008-12-07 15:06:20 +0000 | [diff] [blame] | 142 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 143 | Convenience Functions |
| 144 | ^^^^^^^^^^^^^^^^^^^^^ |
| 145 | |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 146 | This module also defines four shortcut functions: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 147 | |
| 148 | |
| 149 | .. function:: call(*popenargs, **kwargs) |
| 150 | |
| 151 | Run command with arguments. Wait for command to complete, then return the |
| 152 | :attr:`returncode` attribute. |
| 153 | |
| 154 | The arguments are the same as for the Popen constructor. Example:: |
| 155 | |
| 156 | retcode = call(["ls", "-l"]) |
| 157 | |
Philip Jenvey | ab7481a | 2009-05-22 05:46:35 +0000 | [diff] [blame] | 158 | .. warning:: |
| 159 | |
| 160 | Like :meth:`Popen.wait`, this will deadlock if the child process |
| 161 | generates enough output to a stdout or stderr pipe such that it blocks |
| 162 | waiting for the OS pipe buffer to accept more data. |
| 163 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 164 | |
| 165 | .. function:: check_call(*popenargs, **kwargs) |
| 166 | |
| 167 | Run command with arguments. Wait for command to complete. If the exit code was |
Benjamin Peterson | e5384b0 | 2008-10-04 22:00:42 +0000 | [diff] [blame] | 168 | zero then return, otherwise raise :exc:`CalledProcessError`. The |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 169 | :exc:`CalledProcessError` object will have the return code in the |
| 170 | :attr:`returncode` attribute. |
| 171 | |
| 172 | The arguments are the same as for the Popen constructor. Example:: |
| 173 | |
| 174 | check_call(["ls", "-l"]) |
| 175 | |
Philip Jenvey | ab7481a | 2009-05-22 05:46:35 +0000 | [diff] [blame] | 176 | .. warning:: |
| 177 | |
| 178 | See the warning for :func:`call`. |
| 179 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 180 | |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 181 | .. function:: check_output(*popenargs, **kwargs) |
| 182 | |
| 183 | Run command with arguments and return its output as a byte string. |
| 184 | |
Benjamin Peterson | aa06900 | 2009-01-23 03:26:36 +0000 | [diff] [blame] | 185 | If the exit code was non-zero it raises a :exc:`CalledProcessError`. The |
| 186 | :exc:`CalledProcessError` object will have the return code in the |
| 187 | :attr:`returncode` |
| 188 | attribute and output in the :attr:`output` attribute. |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 189 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 190 | The arguments are the same as for the :class:`Popen` constructor. Example:: |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 191 | |
| 192 | >>> subprocess.check_output(["ls", "-l", "/dev/null"]) |
| 193 | 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' |
| 194 | |
| 195 | The stdout argument is not allowed as it is used internally. |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 196 | To capture standard error in the result, use ``stderr=subprocess.STDOUT``:: |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 197 | |
| 198 | >>> subprocess.check_output( |
Mark Dickinson | 934896d | 2009-02-21 20:59:32 +0000 | [diff] [blame] | 199 | ["/bin/sh", "-c", "ls non_existent_file ; exit 0"], |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 200 | stderr=subprocess.STDOUT) |
Mark Dickinson | 934896d | 2009-02-21 20:59:32 +0000 | [diff] [blame] | 201 | 'ls: non_existent_file: No such file or directory\n' |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 202 | |
| 203 | .. versionadded:: 3.1 |
| 204 | |
| 205 | |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 206 | .. function:: getstatusoutput(cmd) |
| 207 | Return ``(status, output)`` of executing *cmd* in a shell. |
| 208 | |
| 209 | Execute the string *cmd* in a shell with :func:`os.popen` and return a 2-tuple |
| 210 | ``(status, output)``. *cmd* is actually run as ``{ cmd ; } 2>&1``, so that the |
| 211 | returned output will contain output or error messages. A trailing newline is |
| 212 | stripped from the output. The exit status for the command can be interpreted |
| 213 | according to the rules for the C function :cfunc:`wait`. Example:: |
| 214 | |
| 215 | >>> import subprocess |
| 216 | >>> subprocess.getstatusoutput('ls /bin/ls') |
| 217 | (0, '/bin/ls') |
| 218 | >>> subprocess.getstatusoutput('cat /bin/junk') |
| 219 | (256, 'cat: /bin/junk: No such file or directory') |
| 220 | >>> subprocess.getstatusoutput('/bin/junk') |
| 221 | (256, 'sh: /bin/junk: not found') |
| 222 | |
Georg Brandl | 7d41890 | 2008-12-27 19:08:11 +0000 | [diff] [blame] | 223 | Availability: UNIX. |
| 224 | |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 225 | |
| 226 | .. function:: getoutput(cmd) |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 227 | Return output (stdout and stderr) of executing *cmd* in a shell. |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 228 | |
| 229 | Like :func:`getstatusoutput`, except the exit status is ignored and the return |
| 230 | value is a string containing the command's output. Example:: |
| 231 | |
| 232 | >>> import subprocess |
| 233 | >>> subprocess.getoutput('ls /bin/ls') |
| 234 | '/bin/ls' |
| 235 | |
Georg Brandl | 7d41890 | 2008-12-27 19:08:11 +0000 | [diff] [blame] | 236 | Availability: UNIX. |
| 237 | |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 238 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 239 | Exceptions |
| 240 | ^^^^^^^^^^ |
| 241 | |
| 242 | Exceptions raised in the child process, before the new program has started to |
| 243 | execute, will be re-raised in the parent. Additionally, the exception object |
| 244 | will have one extra attribute called :attr:`child_traceback`, which is a string |
| 245 | containing traceback information from the childs point of view. |
| 246 | |
| 247 | The most common exception raised is :exc:`OSError`. This occurs, for example, |
| 248 | when trying to execute a non-existent file. Applications should prepare for |
| 249 | :exc:`OSError` exceptions. |
| 250 | |
| 251 | A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid |
| 252 | arguments. |
| 253 | |
| 254 | check_call() will raise :exc:`CalledProcessError`, if the called process returns |
| 255 | a non-zero return code. |
| 256 | |
| 257 | |
| 258 | Security |
| 259 | ^^^^^^^^ |
| 260 | |
| 261 | Unlike some other popen functions, this implementation will never call /bin/sh |
| 262 | implicitly. This means that all characters, including shell metacharacters, can |
| 263 | safely be passed to child processes. |
| 264 | |
| 265 | |
| 266 | Popen Objects |
| 267 | ------------- |
| 268 | |
| 269 | Instances of the :class:`Popen` class have the following methods: |
| 270 | |
| 271 | |
| 272 | .. method:: Popen.poll() |
| 273 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 274 | Check if child process has terminated. Set and return :attr:`returncode` |
| 275 | attribute. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 276 | |
| 277 | |
| 278 | .. method:: Popen.wait() |
| 279 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 280 | Wait for child process to terminate. Set and return :attr:`returncode` |
| 281 | attribute. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 282 | |
Georg Brandl | 734e268 | 2008-08-12 08:18:18 +0000 | [diff] [blame] | 283 | .. warning:: |
| 284 | |
| 285 | This will deadlock if the child process generates enough output to a |
| 286 | stdout or stderr pipe such that it blocks waiting for the OS pipe buffer |
| 287 | to accept more data. Use :meth:`communicate` to avoid that. |
| 288 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 289 | |
| 290 | .. method:: Popen.communicate(input=None) |
| 291 | |
| 292 | Interact with process: Send data to stdin. Read data from stdout and stderr, |
| 293 | until end-of-file is reached. Wait for process to terminate. The optional |
Georg Brandl | e11787a | 2008-07-01 19:10:52 +0000 | [diff] [blame] | 294 | *input* argument should be a byte string to be sent to the child process, or |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 295 | ``None``, if no data should be sent to the child. |
| 296 | |
Georg Brandl | af265f4 | 2008-12-07 15:06:20 +0000 | [diff] [blame] | 297 | :meth:`communicate` returns a tuple ``(stdoutdata, stderrdata)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 298 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 299 | Note that if you want to send data to the process's stdin, you need to create |
| 300 | the Popen object with ``stdin=PIPE``. Similarly, to get anything other than |
| 301 | ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or |
| 302 | ``stderr=PIPE`` too. |
| 303 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 304 | .. note:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 305 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 306 | The data read is buffered in memory, so do not use this method if the data |
| 307 | size is large or unlimited. |
| 308 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 309 | |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 310 | .. method:: Popen.send_signal(signal) |
| 311 | |
| 312 | Sends the signal *signal* to the child. |
| 313 | |
| 314 | .. note:: |
| 315 | |
| 316 | On Windows only SIGTERM is supported so far. It's an alias for |
| 317 | :meth:`terminate`. |
| 318 | |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 319 | |
| 320 | .. method:: Popen.terminate() |
| 321 | |
| 322 | Stop the child. On Posix OSs the method sends SIGTERM to the |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 323 | child. On Windows the Win32 API function :cfunc:`TerminateProcess` is called |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 324 | to stop the child. |
| 325 | |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 326 | |
| 327 | .. method:: Popen.kill() |
| 328 | |
| 329 | Kills the child. On Posix OSs the function sends SIGKILL to the child. |
| 330 | On Windows :meth:`kill` is an alias for :meth:`terminate`. |
| 331 | |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 332 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 333 | The following attributes are also available: |
| 334 | |
Georg Brandl | 734e268 | 2008-08-12 08:18:18 +0000 | [diff] [blame] | 335 | .. warning:: |
| 336 | |
Georg Brandl | e720c0a | 2009-04-27 16:20:50 +0000 | [diff] [blame] | 337 | Use :meth:`communicate` rather than :attr:`.stdin.write <stdin>`, |
| 338 | :attr:`.stdout.read <stdout>` or :attr:`.stderr.read <stderr>` to avoid |
| 339 | deadlocks due to any of the other OS pipe buffers filling up and blocking the |
| 340 | child process. |
Georg Brandl | 734e268 | 2008-08-12 08:18:18 +0000 | [diff] [blame] | 341 | |
| 342 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 343 | .. attribute:: Popen.stdin |
| 344 | |
Georg Brandl | af265f4 | 2008-12-07 15:06:20 +0000 | [diff] [blame] | 345 | If the *stdin* argument was :data:`PIPE`, this attribute is a file object |
| 346 | that provides input to the child process. Otherwise, it is ``None``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 347 | |
| 348 | |
| 349 | .. attribute:: Popen.stdout |
| 350 | |
Georg Brandl | af265f4 | 2008-12-07 15:06:20 +0000 | [diff] [blame] | 351 | If the *stdout* argument was :data:`PIPE`, this attribute is a file object |
| 352 | that provides output from the child process. Otherwise, it is ``None``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 353 | |
| 354 | |
| 355 | .. attribute:: Popen.stderr |
| 356 | |
Georg Brandl | af265f4 | 2008-12-07 15:06:20 +0000 | [diff] [blame] | 357 | If the *stderr* argument was :data:`PIPE`, this attribute is a file object |
| 358 | that provides error output from the child process. Otherwise, it is |
| 359 | ``None``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 360 | |
| 361 | |
| 362 | .. attribute:: Popen.pid |
| 363 | |
| 364 | The process ID of the child process. |
| 365 | |
| 366 | |
| 367 | .. attribute:: Popen.returncode |
| 368 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 369 | The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly |
| 370 | by :meth:`communicate`). A ``None`` value indicates that the process |
| 371 | hasn't terminated yet. |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 372 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 373 | A negative value ``-N`` indicates that the child was terminated by signal |
| 374 | ``N`` (Unix only). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 375 | |
| 376 | |
Benjamin Peterson | dcf97b9 | 2008-07-02 17:30:14 +0000 | [diff] [blame] | 377 | .. _subprocess-replacements: |
| 378 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 379 | Replacing Older Functions with the subprocess Module |
| 380 | ---------------------------------------------------- |
| 381 | |
| 382 | In this section, "a ==> b" means that b can be used as a replacement for a. |
| 383 | |
| 384 | .. note:: |
| 385 | |
| 386 | All functions in this section fail (more or less) silently if the executed |
| 387 | program cannot be found; this module raises an :exc:`OSError` exception. |
| 388 | |
| 389 | In the following examples, we assume that the subprocess module is imported with |
| 390 | "from subprocess import \*". |
| 391 | |
| 392 | |
| 393 | Replacing /bin/sh shell backquote |
| 394 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 395 | |
| 396 | :: |
| 397 | |
| 398 | output=`mycmd myarg` |
| 399 | ==> |
| 400 | output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] |
| 401 | |
| 402 | |
Benjamin Peterson | f10a79a | 2008-10-11 00:49:57 +0000 | [diff] [blame] | 403 | Replacing shell pipeline |
| 404 | ^^^^^^^^^^^^^^^^^^^^^^^^ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 405 | |
| 406 | :: |
| 407 | |
| 408 | output=`dmesg | grep hda` |
| 409 | ==> |
| 410 | p1 = Popen(["dmesg"], stdout=PIPE) |
| 411 | p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) |
| 412 | output = p2.communicate()[0] |
| 413 | |
| 414 | |
Benjamin Peterson | 87c8d87 | 2009-06-11 22:54:11 +0000 | [diff] [blame] | 415 | Replacing :func:`os.system` |
| 416 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 417 | |
| 418 | :: |
| 419 | |
| 420 | sts = os.system("mycmd" + " myarg") |
| 421 | ==> |
| 422 | p = Popen("mycmd" + " myarg", shell=True) |
| 423 | sts = os.waitpid(p.pid, 0) |
| 424 | |
| 425 | Notes: |
| 426 | |
| 427 | * Calling the program through the shell is usually not required. |
| 428 | |
| 429 | * It's easier to look at the :attr:`returncode` attribute than the exit status. |
| 430 | |
| 431 | A more realistic example would look like this:: |
| 432 | |
| 433 | try: |
| 434 | retcode = call("mycmd" + " myarg", shell=True) |
| 435 | if retcode < 0: |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 436 | print("Child was terminated by signal", -retcode, file=sys.stderr) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 437 | else: |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 438 | print("Child returned", retcode, file=sys.stderr) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 439 | except OSError as e: |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 440 | print("Execution failed:", e, file=sys.stderr) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 441 | |
| 442 | |
Benjamin Peterson | 87c8d87 | 2009-06-11 22:54:11 +0000 | [diff] [blame] | 443 | Replacing the :func:`os.spawn <os.spawnl>` family |
| 444 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 445 | |
| 446 | P_NOWAIT example:: |
| 447 | |
| 448 | pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") |
| 449 | ==> |
| 450 | pid = Popen(["/bin/mycmd", "myarg"]).pid |
| 451 | |
| 452 | P_WAIT example:: |
| 453 | |
| 454 | retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg") |
| 455 | ==> |
| 456 | retcode = call(["/bin/mycmd", "myarg"]) |
| 457 | |
| 458 | Vector example:: |
| 459 | |
| 460 | os.spawnvp(os.P_NOWAIT, path, args) |
| 461 | ==> |
| 462 | Popen([path] + args[1:]) |
| 463 | |
| 464 | Environment example:: |
| 465 | |
| 466 | os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env) |
| 467 | ==> |
| 468 | Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}) |
| 469 | |
| 470 | |
Benjamin Peterson | 87c8d87 | 2009-06-11 22:54:11 +0000 | [diff] [blame] | 471 | |
| 472 | Replacing :func:`os.popen`, :func:`os.popen2`, :func:`os.popen3` |
| 473 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 474 | |
| 475 | :: |
| 476 | |
Benjamin Peterson | 87c8d87 | 2009-06-11 22:54:11 +0000 | [diff] [blame] | 477 | (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 478 | ==> |
Benjamin Peterson | 87c8d87 | 2009-06-11 22:54:11 +0000 | [diff] [blame] | 479 | p = Popen(cmd, shell=True, bufsize=bufsize, |
| 480 | stdin=PIPE, stdout=PIPE, close_fds=True) |
| 481 | (child_stdin, child_stdout) = (p.stdin, p.stdout) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 482 | |
| 483 | :: |
| 484 | |
Benjamin Peterson | 87c8d87 | 2009-06-11 22:54:11 +0000 | [diff] [blame] | 485 | (child_stdin, |
| 486 | child_stdout, |
| 487 | child_stderr) = os.popen3(cmd, mode, bufsize) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 488 | ==> |
Benjamin Peterson | 87c8d87 | 2009-06-11 22:54:11 +0000 | [diff] [blame] | 489 | p = Popen(cmd, shell=True, bufsize=bufsize, |
| 490 | stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) |
| 491 | (child_stdin, |
| 492 | child_stdout, |
| 493 | child_stderr) = (p.stdin, p.stdout, p.stderr) |
| 494 | |
| 495 | :: |
| 496 | |
| 497 | (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize) |
| 498 | ==> |
| 499 | p = Popen(cmd, shell=True, bufsize=bufsize, |
| 500 | stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) |
| 501 | (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout) |
| 502 | |
| 503 | Return code handling translates as follows:: |
| 504 | |
| 505 | pipe = os.popen(cmd, 'w') |
| 506 | ... |
| 507 | rc = pipe.close() |
| 508 | if rc != None and rc % 256: |
| 509 | print "There were some errors" |
| 510 | ==> |
| 511 | process = Popen(cmd, 'w', stdin=PIPE) |
| 512 | ... |
| 513 | process.stdin.close() |
| 514 | if process.wait() != 0: |
| 515 | print "There were some errors" |
| 516 | |
| 517 | |
| 518 | Replacing functions from the :mod:`popen2` module |
| 519 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 520 | |
| 521 | .. note:: |
| 522 | |
| 523 | If the cmd argument to popen2 functions is a string, the command is executed |
| 524 | through /bin/sh. If it is a list, the command is directly executed. |
| 525 | |
| 526 | :: |
| 527 | |
| 528 | (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode) |
| 529 | ==> |
| 530 | p = Popen(["somestring"], shell=True, bufsize=bufsize, |
| 531 | stdin=PIPE, stdout=PIPE, close_fds=True) |
| 532 | (child_stdout, child_stdin) = (p.stdout, p.stdin) |
| 533 | |
| 534 | :: |
| 535 | |
| 536 | (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode) |
| 537 | ==> |
| 538 | p = Popen(["mycmd", "myarg"], bufsize=bufsize, |
| 539 | stdin=PIPE, stdout=PIPE, close_fds=True) |
| 540 | (child_stdout, child_stdin) = (p.stdout, p.stdin) |
| 541 | |
| 542 | :class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as |
| 543 | :class:`subprocess.Popen`, except that: |
| 544 | |
| 545 | * :class:`Popen` raises an exception if the execution fails. |
| 546 | |
| 547 | * the *capturestderr* argument is replaced with the *stderr* argument. |
| 548 | |
| 549 | * ``stdin=PIPE`` and ``stdout=PIPE`` must be specified. |
| 550 | |
| 551 | * popen2 closes all file descriptors by default, but you have to specify |
| 552 | ``close_fds=True`` with :class:`Popen`. |