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