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