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