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