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 | 8edd99d | 2010-12-14 13:43:30 +0000 | [diff] [blame] | 31 | .. class:: Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=()) |
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 | |
R. David Murray | c7399d0 | 2010-11-12 00:35:31 +0000 | [diff] [blame] | 79 | .. warning:: |
| 80 | |
| 81 | Executing shell commands that incorporate unsanitized input from an |
| 82 | untrusted source makes a program vulnerable to `shell injection |
| 83 | <http://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_, |
| 84 | a serious security flaw which can result in arbitrary command execution. |
| 85 | For this reason, the use of *shell=True* is **strongly discouraged** in cases |
| 86 | where the command string is constructed from external input:: |
| 87 | |
| 88 | >>> from subprocess import call |
| 89 | >>> filename = input("What file would you like to display?\n") |
| 90 | What file would you like to display? |
| 91 | non_existent; rm -rf / # |
| 92 | >>> call("cat " + filename, shell=True) # Uh-oh. This will end badly... |
| 93 | |
| 94 | *shell=False* does not suffer from this vulnerability; the above Note may be |
| 95 | helpful in getting code using *shell=False* to work. |
| 96 | |
Eli Bendersky | 046a764 | 2011-04-15 07:23:26 +0300 | [diff] [blame] | 97 | On Windows: the :class:`Popen` class uses CreateProcess() to execute the |
| 98 | child program, which operates on strings. If *args* is a sequence, it will |
| 99 | be converted to a string in a manner described in |
| 100 | :ref:`converting-argument-sequence`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 101 | |
| 102 | *bufsize*, if given, has the same meaning as the corresponding argument to the |
| 103 | built-in open() function: :const:`0` means unbuffered, :const:`1` means line |
| 104 | buffered, any other positive value means use a buffer of (approximately) that |
| 105 | size. A negative *bufsize* means to use the system default, which usually means |
| 106 | fully buffered. The default value for *bufsize* is :const:`0` (unbuffered). |
| 107 | |
Antoine Pitrou | 4b87620 | 2010-06-02 17:10:49 +0000 | [diff] [blame] | 108 | .. note:: |
| 109 | |
| 110 | If you experience performance issues, it is recommended that you try to |
| 111 | enable buffering by setting *bufsize* to either -1 or a large enough |
| 112 | positive value (such as 4096). |
| 113 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 114 | The *executable* argument specifies the program to execute. It is very seldom |
| 115 | needed: Usually, the program to execute is defined by the *args* argument. If |
| 116 | ``shell=True``, the *executable* argument specifies which shell to use. On Unix, |
| 117 | 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] | 118 | specified by the :envvar:`COMSPEC` environment variable. The only reason you |
| 119 | would need to specify ``shell=True`` on Windows is where the command you |
| 120 | wish to execute is actually built in to the shell, eg ``dir``, ``copy``. |
| 121 | You don't need ``shell=True`` to run a batch file, nor to run a console-based |
| 122 | executable. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 123 | |
| 124 | *stdin*, *stdout* and *stderr* specify the executed programs' standard input, |
Georg Brandl | af265f4 | 2008-12-07 15:06:20 +0000 | [diff] [blame] | 125 | standard output and standard error file handles, respectively. Valid values |
| 126 | are :data:`PIPE`, an existing file descriptor (a positive integer), an |
Antoine Pitrou | 11cb961 | 2010-09-15 11:11:28 +0000 | [diff] [blame] | 127 | existing :term:`file object`, and ``None``. :data:`PIPE` indicates that a |
| 128 | new pipe to the child should be created. With ``None``, no redirection will |
| 129 | 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] | 130 | *stderr* can be :data:`STDOUT`, which indicates that the stderr data from the |
| 131 | applications should be captured into the same file handle as for stdout. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 132 | |
| 133 | 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] | 134 | child process just before the child is executed. |
| 135 | (Unix only) |
| 136 | |
| 137 | .. warning:: |
| 138 | |
| 139 | The *preexec_fn* parameter is not safe to use in the presence of threads |
| 140 | in your application. The child process could deadlock before exec is |
| 141 | called. |
| 142 | If you must use it, keep it trivial! Minimize the number of libraries |
| 143 | you call into. |
| 144 | |
| 145 | .. note:: |
| 146 | |
| 147 | If you need to modify the environment for the child use the *env* |
| 148 | parameter rather than doing it in a *preexec_fn*. |
| 149 | The *start_new_session* parameter can take the place of a previously |
| 150 | common use of *preexec_fn* to call os.setsid() in the child. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 151 | |
| 152 | If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and |
| 153 | :const:`2` will be closed before the child process is executed. (Unix only). |
Gregory P. Smith | 8edd99d | 2010-12-14 13:43:30 +0000 | [diff] [blame] | 154 | The default varies by platform: Always true on Unix. On Windows it is |
| 155 | true when *stdin*/*stdout*/*stderr* are :const:`None`, false otherwise. |
Gregory P. Smith | d23047b | 2010-12-04 09:10:44 +0000 | [diff] [blame] | 156 | On Windows, if *close_fds* is true then no handles will be inherited by the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 157 | child process. Note that on Windows, you cannot set *close_fds* to true and |
| 158 | also redirect the standard handles by setting *stdin*, *stdout* or *stderr*. |
| 159 | |
Gregory P. Smith | 8edd99d | 2010-12-14 13:43:30 +0000 | [diff] [blame] | 160 | .. versionchanged:: 3.2 |
| 161 | The default for *close_fds* was changed from :const:`False` to |
| 162 | what is described above. |
| 163 | |
| 164 | *pass_fds* is an optional sequence of file descriptors to keep open |
| 165 | between the parent and child. Providing any *pass_fds* forces |
| 166 | *close_fds* to be :const:`True`. (Unix only) |
| 167 | |
| 168 | .. versionadded:: 3.2 |
| 169 | The *pass_fds* parameter was added. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 170 | |
| 171 | If *cwd* is not ``None``, the child's current directory will be changed to *cwd* |
| 172 | before it is executed. Note that this directory is not considered when |
| 173 | searching the executable, so you can't specify the program's path relative to |
| 174 | *cwd*. |
| 175 | |
Gregory P. Smith | fb94c5f | 2010-03-14 06:49:55 +0000 | [diff] [blame] | 176 | If *restore_signals* is True (the default) all signals that Python has set to |
| 177 | SIG_IGN are restored to SIG_DFL in the child process before the exec. |
| 178 | Currently this includes the SIGPIPE, SIGXFZ and SIGXFSZ signals. |
| 179 | (Unix only) |
| 180 | |
| 181 | .. versionchanged:: 3.2 |
| 182 | *restore_signals* was added. |
| 183 | |
| 184 | If *start_new_session* is True the setsid() system call will be made in the |
| 185 | child process prior to the execution of the subprocess. (Unix only) |
| 186 | |
| 187 | .. versionchanged:: 3.2 |
| 188 | *start_new_session* was added. |
| 189 | |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 190 | 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] | 191 | variables for the new process; these are used instead of the default |
| 192 | behavior of inheriting the current process' environment. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 193 | |
R. David Murray | 1055e89 | 2009-04-16 18:15:32 +0000 | [diff] [blame] | 194 | .. note:: |
R. David Murray | f4ac149 | 2009-04-15 22:35:15 +0000 | [diff] [blame] | 195 | |
Georg Brandl | 2708f3a | 2009-12-20 14:38:23 +0000 | [diff] [blame] | 196 | If specified, *env* must provide any variables required for the program to |
| 197 | execute. On Windows, in order to run a `side-by-side assembly`_ the |
| 198 | specified *env* **must** include a valid :envvar:`SystemRoot`. |
R. David Murray | f4ac149 | 2009-04-15 22:35:15 +0000 | [diff] [blame] | 199 | |
R. David Murray | 1055e89 | 2009-04-16 18:15:32 +0000 | [diff] [blame] | 200 | .. _side-by-side assembly: http://en.wikipedia.org/wiki/Side-by-Side_Assembly |
| 201 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 202 | If *universal_newlines* is :const:`True`, the file objects stdout and stderr are |
| 203 | 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] | 204 | 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] | 205 | Windows convention. All of these external representations are seen as ``'\n'`` |
| 206 | by the Python program. |
| 207 | |
| 208 | .. note:: |
| 209 | |
Georg Brandl | 7f01a13 | 2009-09-16 15:58:14 +0000 | [diff] [blame] | 210 | This feature is only available if Python is built with universal newline |
| 211 | support (the default). Also, the newlines attribute of the file objects |
| 212 | :attr:`stdout`, :attr:`stdin` and :attr:`stderr` are not updated by the |
| 213 | :meth:`communicate` method. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 214 | |
Brian Curtin | e6242d7 | 2011-04-29 22:17:51 -0500 | [diff] [blame] | 215 | If given, *startupinfo* will be a :class:`STARTUPINFO` object, which is |
| 216 | passed to the underlying ``CreateProcess`` function. |
Brian Curtin | 3040193 | 2011-04-29 22:20:57 -0500 | [diff] [blame] | 217 | *creationflags*, if given, can be :data:`CREATE_NEW_CONSOLE` or |
| 218 | :data:`CREATE_NEW_PROCESS_GROUP`. (Windows only) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 219 | |
Brian Curtin | 79cdb66 | 2010-12-03 02:46:02 +0000 | [diff] [blame] | 220 | Popen objects are supported as context managers via the :keyword:`with` statement, |
| 221 | closing any open file descriptors on exit. |
| 222 | :: |
| 223 | |
| 224 | with Popen(["ifconfig"], stdout=PIPE) as proc: |
| 225 | log.write(proc.stdout.read()) |
| 226 | |
| 227 | .. versionchanged:: 3.2 |
| 228 | Added context manager support. |
| 229 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 230 | |
Georg Brandl | af265f4 | 2008-12-07 15:06:20 +0000 | [diff] [blame] | 231 | .. data:: PIPE |
| 232 | |
| 233 | Special value that can be used as the *stdin*, *stdout* or *stderr* argument |
| 234 | to :class:`Popen` and indicates that a pipe to the standard stream should be |
| 235 | opened. |
| 236 | |
| 237 | |
| 238 | .. data:: STDOUT |
| 239 | |
| 240 | Special value that can be used as the *stderr* argument to :class:`Popen` and |
| 241 | indicates that standard error should go into the same handle as standard |
| 242 | output. |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 243 | |
Georg Brandl | af265f4 | 2008-12-07 15:06:20 +0000 | [diff] [blame] | 244 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 245 | Convenience Functions |
| 246 | ^^^^^^^^^^^^^^^^^^^^^ |
| 247 | |
Ezio Melotti | 8dfcab0 | 2011-04-19 23:15:13 +0300 | [diff] [blame] | 248 | This module also defines the following shortcut functions: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 249 | |
| 250 | |
| 251 | .. function:: call(*popenargs, **kwargs) |
| 252 | |
| 253 | Run command with arguments. Wait for command to complete, then return the |
| 254 | :attr:`returncode` attribute. |
| 255 | |
Benjamin Peterson | 21896a3 | 2010-03-21 22:03:03 +0000 | [diff] [blame] | 256 | The arguments are the same as for the :class:`Popen` constructor. Example:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 257 | |
Georg Brandl | 2708f3a | 2009-12-20 14:38:23 +0000 | [diff] [blame] | 258 | >>> retcode = subprocess.call(["ls", "-l"]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 259 | |
Philip Jenvey | ab7481a | 2009-05-22 05:46:35 +0000 | [diff] [blame] | 260 | .. warning:: |
| 261 | |
Philip Jenvey | b089684 | 2009-12-03 02:29:36 +0000 | [diff] [blame] | 262 | Like :meth:`Popen.wait`, this will deadlock when using |
| 263 | ``stdout=PIPE`` and/or ``stderr=PIPE`` and the child process |
| 264 | generates enough output to a pipe such that it blocks waiting |
| 265 | for the OS pipe buffer to accept more data. |
Philip Jenvey | ab7481a | 2009-05-22 05:46:35 +0000 | [diff] [blame] | 266 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 267 | |
| 268 | .. function:: check_call(*popenargs, **kwargs) |
| 269 | |
| 270 | 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] | 271 | zero then return, otherwise raise :exc:`CalledProcessError`. The |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 272 | :exc:`CalledProcessError` object will have the return code in the |
| 273 | :attr:`returncode` attribute. |
| 274 | |
Benjamin Peterson | 21896a3 | 2010-03-21 22:03:03 +0000 | [diff] [blame] | 275 | The arguments are the same as for the :class:`Popen` constructor. Example:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 276 | |
Georg Brandl | 2708f3a | 2009-12-20 14:38:23 +0000 | [diff] [blame] | 277 | >>> subprocess.check_call(["ls", "-l"]) |
| 278 | 0 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 279 | |
Philip Jenvey | ab7481a | 2009-05-22 05:46:35 +0000 | [diff] [blame] | 280 | .. warning:: |
| 281 | |
| 282 | See the warning for :func:`call`. |
| 283 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 284 | |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 285 | .. function:: check_output(*popenargs, **kwargs) |
| 286 | |
| 287 | Run command with arguments and return its output as a byte string. |
| 288 | |
Benjamin Peterson | aa06900 | 2009-01-23 03:26:36 +0000 | [diff] [blame] | 289 | If the exit code was non-zero it raises a :exc:`CalledProcessError`. The |
| 290 | :exc:`CalledProcessError` object will have the return code in the |
| 291 | :attr:`returncode` |
| 292 | attribute and output in the :attr:`output` attribute. |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 293 | |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 294 | The arguments are the same as for the :class:`Popen` constructor. Example:: |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 295 | |
| 296 | >>> subprocess.check_output(["ls", "-l", "/dev/null"]) |
Georg Brandl | 2708f3a | 2009-12-20 14:38:23 +0000 | [diff] [blame] | 297 | 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] | 298 | |
| 299 | The stdout argument is not allowed as it is used internally. |
Benjamin Peterson | 25c95f1 | 2009-05-08 20:42:26 +0000 | [diff] [blame] | 300 | To capture standard error in the result, use ``stderr=subprocess.STDOUT``:: |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 301 | |
| 302 | >>> subprocess.check_output( |
Georg Brandl | 2708f3a | 2009-12-20 14:38:23 +0000 | [diff] [blame] | 303 | ... ["/bin/sh", "-c", "ls non_existent_file; exit 0"], |
| 304 | ... stderr=subprocess.STDOUT) |
| 305 | b'ls: non_existent_file: No such file or directory\n' |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 306 | |
| 307 | .. versionadded:: 3.1 |
| 308 | |
| 309 | |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 310 | .. function:: getstatusoutput(cmd) |
Georg Brandl | 682d7e0 | 2010-10-06 10:26:05 +0000 | [diff] [blame] | 311 | |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 312 | Return ``(status, output)`` of executing *cmd* in a shell. |
| 313 | |
| 314 | Execute the string *cmd* in a shell with :func:`os.popen` and return a 2-tuple |
| 315 | ``(status, output)``. *cmd* is actually run as ``{ cmd ; } 2>&1``, so that the |
| 316 | returned output will contain output or error messages. A trailing newline is |
| 317 | stripped from the output. The exit status for the command can be interpreted |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 318 | according to the rules for the C function :c:func:`wait`. Example:: |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 319 | |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 320 | >>> subprocess.getstatusoutput('ls /bin/ls') |
| 321 | (0, '/bin/ls') |
| 322 | >>> subprocess.getstatusoutput('cat /bin/junk') |
| 323 | (256, 'cat: /bin/junk: No such file or directory') |
| 324 | >>> subprocess.getstatusoutput('/bin/junk') |
| 325 | (256, 'sh: /bin/junk: not found') |
| 326 | |
Georg Brandl | 7d41890 | 2008-12-27 19:08:11 +0000 | [diff] [blame] | 327 | Availability: UNIX. |
| 328 | |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 329 | |
| 330 | .. function:: getoutput(cmd) |
Georg Brandl | 682d7e0 | 2010-10-06 10:26:05 +0000 | [diff] [blame] | 331 | |
Georg Brandl | f973407 | 2008-12-07 15:30:06 +0000 | [diff] [blame] | 332 | Return output (stdout and stderr) of executing *cmd* in a shell. |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 333 | |
| 334 | Like :func:`getstatusoutput`, except the exit status is ignored and the return |
| 335 | value is a string containing the command's output. Example:: |
| 336 | |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 337 | >>> subprocess.getoutput('ls /bin/ls') |
| 338 | '/bin/ls' |
| 339 | |
Georg Brandl | 7d41890 | 2008-12-27 19:08:11 +0000 | [diff] [blame] | 340 | Availability: UNIX. |
| 341 | |
Brett Cannon | a23810f | 2008-05-26 19:04:21 +0000 | [diff] [blame] | 342 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 343 | Exceptions |
| 344 | ^^^^^^^^^^ |
| 345 | |
| 346 | Exceptions raised in the child process, before the new program has started to |
| 347 | execute, will be re-raised in the parent. Additionally, the exception object |
| 348 | will have one extra attribute called :attr:`child_traceback`, which is a string |
Georg Brandl | 8167561 | 2010-08-26 14:30:56 +0000 | [diff] [blame] | 349 | containing traceback information from the child's point of view. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 350 | |
| 351 | The most common exception raised is :exc:`OSError`. This occurs, for example, |
| 352 | when trying to execute a non-existent file. Applications should prepare for |
| 353 | :exc:`OSError` exceptions. |
| 354 | |
| 355 | A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid |
| 356 | arguments. |
| 357 | |
| 358 | check_call() will raise :exc:`CalledProcessError`, if the called process returns |
| 359 | a non-zero return code. |
| 360 | |
| 361 | |
| 362 | Security |
| 363 | ^^^^^^^^ |
| 364 | |
| 365 | Unlike some other popen functions, this implementation will never call /bin/sh |
| 366 | implicitly. This means that all characters, including shell metacharacters, can |
| 367 | safely be passed to child processes. |
| 368 | |
| 369 | |
| 370 | Popen Objects |
| 371 | ------------- |
| 372 | |
| 373 | Instances of the :class:`Popen` class have the following methods: |
| 374 | |
| 375 | |
| 376 | .. method:: Popen.poll() |
| 377 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 378 | Check if child process has terminated. Set and return :attr:`returncode` |
| 379 | attribute. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 380 | |
| 381 | |
| 382 | .. method:: Popen.wait() |
| 383 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 384 | Wait for child process to terminate. Set and return :attr:`returncode` |
| 385 | attribute. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 386 | |
Georg Brandl | 734e268 | 2008-08-12 08:18:18 +0000 | [diff] [blame] | 387 | .. warning:: |
| 388 | |
Philip Jenvey | b089684 | 2009-12-03 02:29:36 +0000 | [diff] [blame] | 389 | This will deadlock when using ``stdout=PIPE`` and/or |
| 390 | ``stderr=PIPE`` and the child process generates enough output to |
| 391 | a pipe such that it blocks waiting for the OS pipe buffer to |
| 392 | accept more data. Use :meth:`communicate` to avoid that. |
Georg Brandl | 734e268 | 2008-08-12 08:18:18 +0000 | [diff] [blame] | 393 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 394 | |
| 395 | .. method:: Popen.communicate(input=None) |
| 396 | |
| 397 | Interact with process: Send data to stdin. Read data from stdout and stderr, |
| 398 | 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] | 399 | *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] | 400 | ``None``, if no data should be sent to the child. |
| 401 | |
Georg Brandl | af265f4 | 2008-12-07 15:06:20 +0000 | [diff] [blame] | 402 | :meth:`communicate` returns a tuple ``(stdoutdata, stderrdata)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 403 | |
Guido van Rossum | 0d3fb8a | 2007-11-26 23:23:18 +0000 | [diff] [blame] | 404 | Note that if you want to send data to the process's stdin, you need to create |
| 405 | the Popen object with ``stdin=PIPE``. Similarly, to get anything other than |
| 406 | ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or |
| 407 | ``stderr=PIPE`` too. |
| 408 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 409 | .. note:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 410 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 411 | The data read is buffered in memory, so do not use this method if the data |
| 412 | size is large or unlimited. |
| 413 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 414 | |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 415 | .. method:: Popen.send_signal(signal) |
| 416 | |
| 417 | Sends the signal *signal* to the child. |
| 418 | |
| 419 | .. note:: |
| 420 | |
Brian Curtin | eb24d74 | 2010-04-12 17:16:38 +0000 | [diff] [blame] | 421 | On Windows, SIGTERM is an alias for :meth:`terminate`. CTRL_C_EVENT and |
Senthil Kumaran | 916bd38 | 2010-10-15 12:55:19 +0000 | [diff] [blame] | 422 | CTRL_BREAK_EVENT can be sent to processes started with a *creationflags* |
Brian Curtin | eb24d74 | 2010-04-12 17:16:38 +0000 | [diff] [blame] | 423 | parameter which includes `CREATE_NEW_PROCESS_GROUP`. |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 424 | |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 425 | |
| 426 | .. method:: Popen.terminate() |
| 427 | |
| 428 | Stop the child. On Posix OSs the method sends SIGTERM to the |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 429 | child. On Windows the Win32 API function :c:func:`TerminateProcess` is called |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 430 | to stop the child. |
| 431 | |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 432 | |
| 433 | .. method:: Popen.kill() |
| 434 | |
| 435 | Kills the child. On Posix OSs the function sends SIGKILL to the child. |
| 436 | On Windows :meth:`kill` is an alias for :meth:`terminate`. |
| 437 | |
Christian Heimes | a342c01 | 2008-04-20 21:01:16 +0000 | [diff] [blame] | 438 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 439 | The following attributes are also available: |
| 440 | |
Georg Brandl | 734e268 | 2008-08-12 08:18:18 +0000 | [diff] [blame] | 441 | .. warning:: |
| 442 | |
Georg Brandl | e720c0a | 2009-04-27 16:20:50 +0000 | [diff] [blame] | 443 | Use :meth:`communicate` rather than :attr:`.stdin.write <stdin>`, |
| 444 | :attr:`.stdout.read <stdout>` or :attr:`.stderr.read <stderr>` to avoid |
| 445 | deadlocks due to any of the other OS pipe buffers filling up and blocking the |
| 446 | child process. |
Georg Brandl | 734e268 | 2008-08-12 08:18:18 +0000 | [diff] [blame] | 447 | |
| 448 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 449 | .. attribute:: Popen.stdin |
| 450 | |
Antoine Pitrou | 11cb961 | 2010-09-15 11:11:28 +0000 | [diff] [blame] | 451 | If the *stdin* argument was :data:`PIPE`, this attribute is a :term:`file |
| 452 | object` that provides input to the child process. Otherwise, it is ``None``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 453 | |
| 454 | |
| 455 | .. attribute:: Popen.stdout |
| 456 | |
Antoine Pitrou | 11cb961 | 2010-09-15 11:11:28 +0000 | [diff] [blame] | 457 | If the *stdout* argument was :data:`PIPE`, this attribute is a :term:`file |
| 458 | object` that provides output from the child process. Otherwise, it is ``None``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 459 | |
| 460 | |
| 461 | .. attribute:: Popen.stderr |
| 462 | |
Antoine Pitrou | 11cb961 | 2010-09-15 11:11:28 +0000 | [diff] [blame] | 463 | If the *stderr* argument was :data:`PIPE`, this attribute is a :term:`file |
| 464 | object` that provides error output from the child process. Otherwise, it is |
Georg Brandl | af265f4 | 2008-12-07 15:06:20 +0000 | [diff] [blame] | 465 | ``None``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 466 | |
| 467 | |
| 468 | .. attribute:: Popen.pid |
| 469 | |
| 470 | The process ID of the child process. |
| 471 | |
Georg Brandl | 58bfdca | 2010-03-21 09:50:49 +0000 | [diff] [blame] | 472 | Note that if you set the *shell* argument to ``True``, this is the process ID |
| 473 | of the spawned shell. |
| 474 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 475 | |
| 476 | .. attribute:: Popen.returncode |
| 477 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 478 | The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly |
| 479 | by :meth:`communicate`). A ``None`` value indicates that the process |
| 480 | hasn't terminated yet. |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 481 | |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 482 | A negative value ``-N`` indicates that the child was terminated by signal |
| 483 | ``N`` (Unix only). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 484 | |
| 485 | |
Brian Curtin | e6242d7 | 2011-04-29 22:17:51 -0500 | [diff] [blame] | 486 | Windows Popen Helpers |
| 487 | --------------------- |
| 488 | |
| 489 | The :class:`STARTUPINFO` class and following constants are only available |
| 490 | on Windows. |
| 491 | |
| 492 | .. class:: STARTUPINFO() |
Brian Curtin | 73365dd | 2011-04-29 22:18:33 -0500 | [diff] [blame] | 493 | |
Brian Curtin | e6242d7 | 2011-04-29 22:17:51 -0500 | [diff] [blame] | 494 | Partial support of the Windows |
| 495 | `STARTUPINFO <http://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx>`__ |
| 496 | structure is used for :class:`Popen` creation. |
| 497 | |
| 498 | .. attribute:: dwFlags |
| 499 | |
| 500 | A bit field that determines whether certain :class:`STARTUPINFO` members |
| 501 | are used when the process creates a window. :: |
| 502 | |
| 503 | si = subprocess.STARTUPINFO() |
| 504 | si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW |
| 505 | |
| 506 | .. attribute:: hStdInput |
| 507 | |
| 508 | If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this member is |
| 509 | the standard input handle for the process. If :data:`STARTF_USESTDHANDLES` |
| 510 | is not specified, the default for standard input is the keyboard buffer. |
| 511 | |
| 512 | .. attribute:: hStdOutput |
| 513 | |
| 514 | If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this member is |
| 515 | the standard output handle for the process. Otherwise, this member is |
| 516 | ignored and the default for standard output is the console window's |
| 517 | buffer. |
| 518 | |
| 519 | .. attribute:: hStdError |
| 520 | |
| 521 | If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this member is |
| 522 | the standard error handle for the process. Otherwise, this member is |
| 523 | ignored and the default for standard error is the console window's buffer. |
| 524 | |
| 525 | .. attribute:: wShowWindow |
| 526 | |
| 527 | If :attr:`dwFlags` specifies :data:`STARTF_USESHOWWINDOW`, this member |
| 528 | can be any of the values that can be specified in the ``nCmdShow`` |
| 529 | parameter for the |
| 530 | `ShowWindow <http://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx>`__ |
| 531 | function, except for ``SW_SHOWDEFAULT``. Otherwise, this member is |
| 532 | ignored. |
Brian Curtin | 73365dd | 2011-04-29 22:18:33 -0500 | [diff] [blame] | 533 | |
Brian Curtin | e6242d7 | 2011-04-29 22:17:51 -0500 | [diff] [blame] | 534 | :data:`SW_HIDE` is provided for this attribute. It is used when |
| 535 | :class:`Popen` is called with ``shell=True``. |
| 536 | |
| 537 | |
| 538 | Constants |
| 539 | ^^^^^^^^^ |
| 540 | |
| 541 | The :mod:`subprocess` module exposes the following constants. |
| 542 | |
| 543 | .. data:: STD_INPUT_HANDLE |
| 544 | |
| 545 | The standard input device. Initially, this is the console input buffer, |
| 546 | ``CONIN$``. |
| 547 | |
| 548 | .. data:: STD_OUTPUT_HANDLE |
| 549 | |
| 550 | The standard output device. Initially, this is the active console screen |
| 551 | buffer, ``CONOUT$``. |
| 552 | |
| 553 | .. data:: STD_ERROR_HANDLE |
| 554 | |
| 555 | The standard error device. Initially, this is the active console screen |
| 556 | buffer, ``CONOUT$``. |
| 557 | |
| 558 | .. data:: SW_HIDE |
| 559 | |
| 560 | Hides the window. Another window will be activated. |
| 561 | |
| 562 | .. data:: STARTF_USESTDHANDLES |
| 563 | |
| 564 | Specifies that the :attr:`STARTUPINFO.hStdInput`, |
| 565 | :attr:`STARTUPINFO.hStdOutput`, and :attr:`STARTUPINFO.hStdError` members |
| 566 | contain additional information. |
| 567 | |
| 568 | .. data:: STARTF_USESHOWWINDOW |
| 569 | |
| 570 | Specifies that the :attr:`STARTUPINFO.wShowWindow` member contains |
| 571 | additional information. |
| 572 | |
| 573 | .. data:: CREATE_NEW_CONSOLE |
| 574 | |
| 575 | The new process has a new console, instead of inheriting its parent's |
| 576 | console (the default). |
Brian Curtin | 73365dd | 2011-04-29 22:18:33 -0500 | [diff] [blame] | 577 | |
Brian Curtin | e6242d7 | 2011-04-29 22:17:51 -0500 | [diff] [blame] | 578 | This flag is always set when :class:`Popen` is created with ``shell=True``. |
| 579 | |
Brian Curtin | 3040193 | 2011-04-29 22:20:57 -0500 | [diff] [blame] | 580 | .. data:: CREATE_NEW_PROCESS_GROUP |
| 581 | |
| 582 | A :class:`Popen` ``creationflags`` parameter to specify that a new process |
| 583 | group will be created. This flag is necessary for using :func:`os.kill` |
| 584 | on the subprocess. |
| 585 | |
| 586 | This flag is ignored if :data:`CREATE_NEW_CONSOLE` is specified. |
| 587 | |
Brian Curtin | e6242d7 | 2011-04-29 22:17:51 -0500 | [diff] [blame] | 588 | |
Benjamin Peterson | dcf97b9 | 2008-07-02 17:30:14 +0000 | [diff] [blame] | 589 | .. _subprocess-replacements: |
| 590 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 591 | Replacing Older Functions with the subprocess Module |
| 592 | ---------------------------------------------------- |
| 593 | |
| 594 | In this section, "a ==> b" means that b can be used as a replacement for a. |
| 595 | |
| 596 | .. note:: |
| 597 | |
| 598 | All functions in this section fail (more or less) silently if the executed |
| 599 | program cannot be found; this module raises an :exc:`OSError` exception. |
| 600 | |
| 601 | In the following examples, we assume that the subprocess module is imported with |
| 602 | "from subprocess import \*". |
| 603 | |
| 604 | |
| 605 | Replacing /bin/sh shell backquote |
| 606 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 607 | |
| 608 | :: |
| 609 | |
| 610 | output=`mycmd myarg` |
| 611 | ==> |
| 612 | output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] |
| 613 | |
| 614 | |
Benjamin Peterson | f10a79a | 2008-10-11 00:49:57 +0000 | [diff] [blame] | 615 | Replacing shell pipeline |
| 616 | ^^^^^^^^^^^^^^^^^^^^^^^^ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 617 | |
| 618 | :: |
| 619 | |
| 620 | output=`dmesg | grep hda` |
| 621 | ==> |
| 622 | p1 = Popen(["dmesg"], stdout=PIPE) |
| 623 | p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) |
Gregory P. Smith | e09d2f1 | 2011-02-05 21:47:25 +0000 | [diff] [blame] | 624 | p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 625 | output = p2.communicate()[0] |
| 626 | |
Gregory P. Smith | e09d2f1 | 2011-02-05 21:47:25 +0000 | [diff] [blame] | 627 | The p1.stdout.close() call after starting the p2 is important in order for p1 |
| 628 | to receive a SIGPIPE if p2 exits before p1. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 629 | |
Benjamin Peterson | 87c8d87 | 2009-06-11 22:54:11 +0000 | [diff] [blame] | 630 | Replacing :func:`os.system` |
| 631 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 632 | |
| 633 | :: |
| 634 | |
| 635 | sts = os.system("mycmd" + " myarg") |
| 636 | ==> |
| 637 | p = Popen("mycmd" + " myarg", shell=True) |
Alexandre Vassalotti | e52e378 | 2009-07-17 09:18:18 +0000 | [diff] [blame] | 638 | sts = os.waitpid(p.pid, 0)[1] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 639 | |
| 640 | Notes: |
| 641 | |
| 642 | * Calling the program through the shell is usually not required. |
| 643 | |
| 644 | * It's easier to look at the :attr:`returncode` attribute than the exit status. |
| 645 | |
| 646 | A more realistic example would look like this:: |
| 647 | |
| 648 | try: |
| 649 | retcode = call("mycmd" + " myarg", shell=True) |
| 650 | if retcode < 0: |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 651 | print("Child was terminated by signal", -retcode, file=sys.stderr) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 652 | else: |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 653 | print("Child returned", retcode, file=sys.stderr) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 654 | except OSError as e: |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 655 | print("Execution failed:", e, file=sys.stderr) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 656 | |
| 657 | |
Benjamin Peterson | 87c8d87 | 2009-06-11 22:54:11 +0000 | [diff] [blame] | 658 | Replacing the :func:`os.spawn <os.spawnl>` family |
| 659 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 660 | |
| 661 | P_NOWAIT example:: |
| 662 | |
| 663 | pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") |
| 664 | ==> |
| 665 | pid = Popen(["/bin/mycmd", "myarg"]).pid |
| 666 | |
| 667 | P_WAIT example:: |
| 668 | |
| 669 | retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg") |
| 670 | ==> |
| 671 | retcode = call(["/bin/mycmd", "myarg"]) |
| 672 | |
| 673 | Vector example:: |
| 674 | |
| 675 | os.spawnvp(os.P_NOWAIT, path, args) |
| 676 | ==> |
| 677 | Popen([path] + args[1:]) |
| 678 | |
| 679 | Environment example:: |
| 680 | |
| 681 | os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env) |
| 682 | ==> |
| 683 | Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}) |
| 684 | |
| 685 | |
Benjamin Peterson | 87c8d87 | 2009-06-11 22:54:11 +0000 | [diff] [blame] | 686 | |
| 687 | Replacing :func:`os.popen`, :func:`os.popen2`, :func:`os.popen3` |
| 688 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 689 | |
| 690 | :: |
| 691 | |
Benjamin Peterson | 87c8d87 | 2009-06-11 22:54:11 +0000 | [diff] [blame] | 692 | (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 693 | ==> |
Benjamin Peterson | 87c8d87 | 2009-06-11 22:54:11 +0000 | [diff] [blame] | 694 | p = Popen(cmd, shell=True, bufsize=bufsize, |
| 695 | stdin=PIPE, stdout=PIPE, close_fds=True) |
| 696 | (child_stdin, child_stdout) = (p.stdin, p.stdout) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 697 | |
| 698 | :: |
| 699 | |
Benjamin Peterson | 87c8d87 | 2009-06-11 22:54:11 +0000 | [diff] [blame] | 700 | (child_stdin, |
| 701 | child_stdout, |
| 702 | child_stderr) = os.popen3(cmd, mode, bufsize) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 703 | ==> |
Benjamin Peterson | 87c8d87 | 2009-06-11 22:54:11 +0000 | [diff] [blame] | 704 | p = Popen(cmd, shell=True, bufsize=bufsize, |
| 705 | stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) |
| 706 | (child_stdin, |
| 707 | child_stdout, |
| 708 | child_stderr) = (p.stdin, p.stdout, p.stderr) |
| 709 | |
| 710 | :: |
| 711 | |
| 712 | (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize) |
| 713 | ==> |
| 714 | p = Popen(cmd, shell=True, bufsize=bufsize, |
| 715 | stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) |
| 716 | (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout) |
| 717 | |
| 718 | Return code handling translates as follows:: |
| 719 | |
| 720 | pipe = os.popen(cmd, 'w') |
| 721 | ... |
| 722 | rc = pipe.close() |
Stefan Krah | fc9e08d | 2010-07-14 10:16:11 +0000 | [diff] [blame] | 723 | if rc is not None and rc >> 8: |
Ezio Melotti | 985e24d | 2009-09-13 07:54:02 +0000 | [diff] [blame] | 724 | print("There were some errors") |
Benjamin Peterson | 87c8d87 | 2009-06-11 22:54:11 +0000 | [diff] [blame] | 725 | ==> |
| 726 | process = Popen(cmd, 'w', stdin=PIPE) |
| 727 | ... |
| 728 | process.stdin.close() |
| 729 | if process.wait() != 0: |
Ezio Melotti | 985e24d | 2009-09-13 07:54:02 +0000 | [diff] [blame] | 730 | print("There were some errors") |
Benjamin Peterson | 87c8d87 | 2009-06-11 22:54:11 +0000 | [diff] [blame] | 731 | |
| 732 | |
| 733 | Replacing functions from the :mod:`popen2` module |
| 734 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 735 | |
| 736 | .. note:: |
| 737 | |
| 738 | If the cmd argument to popen2 functions is a string, the command is executed |
| 739 | through /bin/sh. If it is a list, the command is directly executed. |
| 740 | |
| 741 | :: |
| 742 | |
| 743 | (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode) |
| 744 | ==> |
| 745 | p = Popen(["somestring"], shell=True, bufsize=bufsize, |
| 746 | stdin=PIPE, stdout=PIPE, close_fds=True) |
| 747 | (child_stdout, child_stdin) = (p.stdout, p.stdin) |
| 748 | |
| 749 | :: |
| 750 | |
| 751 | (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode) |
| 752 | ==> |
| 753 | p = Popen(["mycmd", "myarg"], bufsize=bufsize, |
| 754 | stdin=PIPE, stdout=PIPE, close_fds=True) |
| 755 | (child_stdout, child_stdin) = (p.stdout, p.stdin) |
| 756 | |
| 757 | :class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as |
| 758 | :class:`subprocess.Popen`, except that: |
| 759 | |
| 760 | * :class:`Popen` raises an exception if the execution fails. |
| 761 | |
| 762 | * the *capturestderr* argument is replaced with the *stderr* argument. |
| 763 | |
| 764 | * ``stdin=PIPE`` and ``stdout=PIPE`` must be specified. |
| 765 | |
| 766 | * popen2 closes all file descriptors by default, but you have to specify |
Gregory P. Smith | f560485 | 2010-12-13 06:45:02 +0000 | [diff] [blame] | 767 | ``close_fds=True`` with :class:`Popen` to guarantee this behavior on |
| 768 | all platforms or past Python versions. |
Eli Bendersky | 046a764 | 2011-04-15 07:23:26 +0300 | [diff] [blame] | 769 | |
| 770 | Notes |
| 771 | ----- |
| 772 | |
| 773 | .. _converting-argument-sequence: |
| 774 | |
| 775 | Converting an argument sequence to a string on Windows |
| 776 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 777 | |
| 778 | On Windows, an *args* sequence is converted to a string that can be parsed |
| 779 | using the following rules (which correspond to the rules used by the MS C |
| 780 | runtime): |
| 781 | |
| 782 | 1. Arguments are delimited by white space, which is either a |
| 783 | space or a tab. |
| 784 | |
| 785 | 2. A string surrounded by double quotation marks is |
| 786 | interpreted as a single argument, regardless of white space |
| 787 | contained within. A quoted string can be embedded in an |
| 788 | argument. |
| 789 | |
| 790 | 3. A double quotation mark preceded by a backslash is |
| 791 | interpreted as a literal double quotation mark. |
| 792 | |
| 793 | 4. Backslashes are interpreted literally, unless they |
| 794 | immediately precede a double quotation mark. |
| 795 | |
| 796 | 5. If backslashes immediately precede a double quotation mark, |
| 797 | every pair of backslashes is interpreted as a literal |
| 798 | backslash. If the number of backslashes is odd, the last |
| 799 | backslash escapes the next double quotation mark as |
| 800 | described in rule 3. |
| 801 | |
Eli Bendersky | d211231 | 2011-04-15 07:26:28 +0300 | [diff] [blame] | 802 | |