Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1 | |
| 2 | :mod:`subprocess` --- Subprocess management |
| 3 | =========================================== |
| 4 | |
| 5 | .. module:: subprocess |
| 6 | :synopsis: Subprocess management. |
| 7 | .. moduleauthor:: Peter Åstrand <astrand@lysator.liu.se> |
| 8 | .. sectionauthor:: Peter Åstrand <astrand@lysator.liu.se> |
| 9 | |
| 10 | |
| 11 | .. versionadded:: 2.4 |
| 12 | |
| 13 | The :mod:`subprocess` module allows you to spawn new processes, connect to their |
| 14 | input/output/error pipes, and obtain their return codes. This module intends to |
| 15 | replace several other, older modules and functions, such as:: |
| 16 | |
| 17 | os.system |
| 18 | os.spawn* |
| 19 | os.popen* |
| 20 | popen2.* |
| 21 | commands.* |
| 22 | |
| 23 | Information about how the :mod:`subprocess` module can be used to replace these |
| 24 | modules and functions can be found in the following sections. |
| 25 | |
Georg Brandl | 68b4e74 | 2008-07-01 19:59:00 +0000 | [diff] [blame] | 26 | .. seealso:: |
| 27 | |
| 28 | :pep:`324` -- PEP proposing the subprocess module |
| 29 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 30 | |
| 31 | Using the subprocess Module |
| 32 | --------------------------- |
| 33 | |
Nick Coghlan | 2ed203a | 2011-10-26 21:05:56 +1000 | [diff] [blame] | 34 | The recommended approach to invoking subprocesses is to use the following |
| 35 | convenience functions for all use cases they can handle. For more advanced |
| 36 | use cases, the underlying :class:`Popen` interface can be used directly. |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 37 | |
| 38 | |
Nick Coghlan | 2ed203a | 2011-10-26 21:05:56 +1000 | [diff] [blame] | 39 | .. function:: call(args, *, stdin=None, stdout=None, stderr=None, shell=False) |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 40 | |
| 41 | Run the command described by *args*. Wait for command to complete, then |
| 42 | return the :attr:`returncode` attribute. |
| 43 | |
| 44 | The arguments shown above are merely the most common ones, described below |
Nick Coghlan | 87ba642 | 2011-10-27 17:55:13 +1000 | [diff] [blame] | 45 | in :ref:`frequently-used-arguments` (hence the slightly odd notation in |
| 46 | the abbreviated signature). The full function signature is the same as |
| 47 | that of the :class:`Popen` constructor - this functions passes all |
| 48 | supplied arguments directly through to that interface. |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 49 | |
| 50 | Examples:: |
| 51 | |
| 52 | >>> subprocess.call(["ls", "-l"]) |
| 53 | 0 |
| 54 | |
Nick Coghlan | 2ed203a | 2011-10-26 21:05:56 +1000 | [diff] [blame] | 55 | >>> subprocess.call("exit 1", shell=True) |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 56 | 1 |
| 57 | |
| 58 | .. warning:: |
| 59 | |
Nick Coghlan | 87ba642 | 2011-10-27 17:55:13 +1000 | [diff] [blame] | 60 | Invoking the system shell with ``shell=True`` can be a security hazard |
| 61 | if combined with untrusted input. See the warning under |
| 62 | :ref:`frequently-used-arguments` for details. |
| 63 | |
| 64 | .. note:: |
| 65 | |
Nick Coghlan | 2ed203a | 2011-10-26 21:05:56 +1000 | [diff] [blame] | 66 | Do not use ``stdout=PIPE`` or ``stderr=PIPE`` with this function. As |
| 67 | the pipes are not being read in the current process, the child |
| 68 | process may block if it generates enough output to a pipe to fill up |
| 69 | the OS pipe buffer. |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 70 | |
| 71 | |
Nick Coghlan | 87ba642 | 2011-10-27 17:55:13 +1000 | [diff] [blame] | 72 | .. function:: check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False) |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 73 | |
| 74 | Run command with arguments. Wait for command to complete. If the return |
| 75 | code was zero then return, otherwise raise :exc:`CalledProcessError`. The |
| 76 | :exc:`CalledProcessError` object will have the return code in the |
| 77 | :attr:`returncode` attribute. |
| 78 | |
Nick Coghlan | 87ba642 | 2011-10-27 17:55:13 +1000 | [diff] [blame] | 79 | The arguments shown above are merely the most common ones, described below |
| 80 | in :ref:`frequently-used-arguments` (hence the slightly odd notation in |
| 81 | the abbreviated signature). The full function signature is the same as |
| 82 | that of the :class:`Popen` constructor - this functions passes all |
| 83 | supplied arguments directly through to that interface. |
| 84 | |
| 85 | Examples:: |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 86 | |
| 87 | >>> subprocess.check_call(["ls", "-l"]) |
| 88 | 0 |
| 89 | |
Nick Coghlan | 2ed203a | 2011-10-26 21:05:56 +1000 | [diff] [blame] | 90 | >>> subprocess.check_call("exit 1", shell=True) |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 91 | Traceback (most recent call last): |
| 92 | ... |
Nick Coghlan | 2ed203a | 2011-10-26 21:05:56 +1000 | [diff] [blame] | 93 | subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1 |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 94 | |
| 95 | .. versionadded:: 2.5 |
| 96 | |
| 97 | .. warning:: |
| 98 | |
Nick Coghlan | 87ba642 | 2011-10-27 17:55:13 +1000 | [diff] [blame] | 99 | Invoking the system shell with ``shell=True`` can be a security hazard |
| 100 | if combined with untrusted input. See the warning under |
| 101 | :ref:`frequently-used-arguments` for details. |
| 102 | |
| 103 | .. note:: |
| 104 | |
| 105 | Do not use ``stdout=PIPE`` or ``stderr=PIPE`` with this function. As |
| 106 | the pipes are not being read in the current process, the child |
| 107 | process may block if it generates enough output to a pipe to fill up |
| 108 | the OS pipe buffer. |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 109 | |
| 110 | |
Nick Coghlan | 87ba642 | 2011-10-27 17:55:13 +1000 | [diff] [blame] | 111 | .. function:: check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False) |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 112 | |
| 113 | Run command with arguments and return its output as a byte string. |
| 114 | |
| 115 | If the return code was non-zero it raises a :exc:`CalledProcessError`. The |
| 116 | :exc:`CalledProcessError` object will have the return code in the |
| 117 | :attr:`returncode` attribute and any output in the :attr:`output` |
| 118 | attribute. |
| 119 | |
Nick Coghlan | 87ba642 | 2011-10-27 17:55:13 +1000 | [diff] [blame] | 120 | The arguments shown above are merely the most common ones, described below |
| 121 | in :ref:`frequently-used-arguments` (hence the slightly odd notation in |
| 122 | the abbreviated signature). The full function signature is largely the |
| 123 | same as that of the :class:`Popen` constructor, except that *stdout* is |
| 124 | not permitted as it is used internally. All other supplied arguments are |
| 125 | passed directly through to the :class:`Popen` constructor. |
Nick Coghlan | 2ed203a | 2011-10-26 21:05:56 +1000 | [diff] [blame] | 126 | |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 127 | Examples:: |
| 128 | |
Nick Coghlan | 2ed203a | 2011-10-26 21:05:56 +1000 | [diff] [blame] | 129 | >>> subprocess.check_output(["echo", "Hello World!"]) |
Nick Coghlan | 2ed203a | 2011-10-26 21:05:56 +1000 | [diff] [blame] | 130 | 'Hello World!\n' |
| 131 | |
| 132 | >>> subprocess.check_output("exit 1", shell=True) |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 133 | Traceback (most recent call last): |
| 134 | ... |
Nick Coghlan | 2ed203a | 2011-10-26 21:05:56 +1000 | [diff] [blame] | 135 | subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1 |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 136 | |
Nick Coghlan | 2ed203a | 2011-10-26 21:05:56 +1000 | [diff] [blame] | 137 | To also capture standard error in the result, use |
| 138 | ``stderr=subprocess.STDOUT``:: |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 139 | |
| 140 | >>> subprocess.check_output( |
Nick Coghlan | 2ed203a | 2011-10-26 21:05:56 +1000 | [diff] [blame] | 141 | ... "ls non_existent_file; exit 0", |
| 142 | ... stderr=subprocess.STDOUT, |
| 143 | ... shell=True) |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 144 | 'ls: non_existent_file: No such file or directory\n' |
| 145 | |
| 146 | .. versionadded:: 2.7 |
| 147 | |
Nick Coghlan | 2ed203a | 2011-10-26 21:05:56 +1000 | [diff] [blame] | 148 | .. warning:: |
| 149 | |
Nick Coghlan | 87ba642 | 2011-10-27 17:55:13 +1000 | [diff] [blame] | 150 | Invoking the system shell with ``shell=True`` can be a security hazard |
| 151 | if combined with untrusted input. See the warning under |
| 152 | :ref:`frequently-used-arguments` for details. |
| 153 | |
| 154 | .. note:: |
| 155 | |
Nick Coghlan | 2ed203a | 2011-10-26 21:05:56 +1000 | [diff] [blame] | 156 | Do not use ``stderr=PIPE`` with this function. As the pipe is not being |
| 157 | read in the current process, the child process may block if it |
| 158 | generates enough output to the pipe to fill up the OS pipe buffer. |
| 159 | |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 160 | |
| 161 | .. data:: PIPE |
| 162 | |
| 163 | Special value that can be used as the *stdin*, *stdout* or *stderr* argument |
| 164 | to :class:`Popen` and indicates that a pipe to the standard stream should be |
| 165 | opened. |
| 166 | |
| 167 | |
| 168 | .. data:: STDOUT |
| 169 | |
| 170 | Special value that can be used as the *stderr* argument to :class:`Popen` and |
| 171 | indicates that standard error should go into the same handle as standard |
| 172 | output. |
| 173 | |
| 174 | |
| 175 | .. _frequently-used-arguments: |
| 176 | |
| 177 | Frequently Used Arguments |
| 178 | ^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 179 | |
| 180 | To support a wide variety of use cases, the :class:`Popen` constructor (and |
| 181 | the convenience functions) accept a large number of optional arguments. For |
| 182 | most typical use cases, many of these arguments can be safely left at their |
| 183 | default values. The arguments that are most commonly needed are: |
| 184 | |
Nick Coghlan | 2ed203a | 2011-10-26 21:05:56 +1000 | [diff] [blame] | 185 | *args* is required for all calls and should be a string, or a sequence of |
| 186 | program arguments. Providing a sequence of arguments is generally |
| 187 | preferred, as it allows the module to take care of any required escaping |
| 188 | and quoting of arguments (e.g. to permit spaces in file names). If passing |
| 189 | a single string, either *shell* must be :const:`True` (see below) or else |
| 190 | the string must simply name the program to be executed without specifying |
| 191 | any arguments. |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 192 | |
| 193 | *stdin*, *stdout* and *stderr* specify the executed program's standard input, |
| 194 | standard output and standard error file handles, respectively. Valid values |
| 195 | are :data:`PIPE`, an existing file descriptor (a positive integer), an |
| 196 | existing file object, and ``None``. :data:`PIPE` indicates that a new pipe |
| 197 | to the child should be created. With the default settings of ``None``, no |
| 198 | redirection will occur; the child's file handles will be inherited from the |
| 199 | parent. Additionally, *stderr* can be :data:`STDOUT`, which indicates that |
| 200 | the stderr data from the child process should be captured into the same file |
| 201 | handle as for stdout. |
| 202 | |
Nick Coghlan | 2ed203a | 2011-10-26 21:05:56 +1000 | [diff] [blame] | 203 | When *stdout* or *stderr* are pipes and *universal_newlines* is |
Nick Coghlan | 65ad31a | 2011-10-26 21:15:53 +1000 | [diff] [blame] | 204 | :const:`True` then all line endings will be converted to ``'\n'`` as |
| 205 | described for the universal newlines `'U'`` mode argument to :func:`open`. |
Nick Coghlan | 2ed203a | 2011-10-26 21:05:56 +1000 | [diff] [blame] | 206 | |
| 207 | If *shell* is :const:`True`, the specified command will be executed through |
| 208 | the shell. This can be useful if you are using Python primarily for the |
| 209 | enhanced control flow it offers over most system shells and still want |
| 210 | access to other shell features such as filename wildcards, shell pipes and |
| 211 | environment variable expansion. |
| 212 | |
| 213 | .. warning:: |
| 214 | |
| 215 | Executing shell commands that incorporate unsanitized input from an |
| 216 | untrusted source makes a program vulnerable to `shell injection |
| 217 | <http://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_, |
| 218 | a serious security flaw which can result in arbitrary command execution. |
| 219 | For this reason, the use of *shell=True* is **strongly discouraged** in cases |
| 220 | where the command string is constructed from external input:: |
| 221 | |
| 222 | >>> from subprocess import call |
| 223 | >>> filename = input("What file would you like to display?\n") |
| 224 | What file would you like to display? |
| 225 | non_existent; rm -rf / # |
| 226 | >>> call("cat " + filename, shell=True) # Uh-oh. This will end badly... |
| 227 | |
| 228 | ``shell=False`` disables all shell based features, but does not suffer |
| 229 | from this vulnerability; see the Note in the :class:`Popen` constructor |
| 230 | documentation for helpful hints in getting ``shell=False`` to work. |
| 231 | |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 232 | These options, along with all of the other options, are described in more |
| 233 | detail in the :class:`Popen` constructor documentation. |
| 234 | |
| 235 | |
Sandro Tosi | dbcbd10 | 2011-12-25 11:27:22 +0100 | [diff] [blame] | 236 | Popen Constructor |
Sandro Tosi | 44585bd | 2011-12-25 17:13:10 +0100 | [diff] [blame^] | 237 | ^^^^^^^^^^^^^^^^^ |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 238 | |
| 239 | The underlying process creation and management in this module is handled by |
| 240 | the :class:`Popen` class. It offers a lot of flexibility so that developers |
| 241 | are able to handle the less common cases not covered by the convenience |
| 242 | functions. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 243 | |
| 244 | |
| 245 | .. 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) |
| 246 | |
| 247 | Arguments are: |
| 248 | |
Benjamin Peterson | fff5cf6 | 2008-07-27 15:22:14 +0000 | [diff] [blame] | 249 | *args* should be a string, or a sequence of program arguments. The program |
R. David Murray | fe6e784 | 2009-05-29 19:30:27 +0000 | [diff] [blame] | 250 | to execute is normally the first item in the args sequence or the string if |
| 251 | a string is given, but can be explicitly set by using the *executable* |
| 252 | argument. When *executable* is given, the first item in the args sequence |
| 253 | is still treated by most programs as the command name, which can then be |
| 254 | different from the actual executable name. On Unix, it becomes the display |
| 255 | name for the executing program in utilities such as :program:`ps`. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 256 | |
| 257 | On Unix, with *shell=False* (default): In this case, the Popen class uses |
| 258 | :meth:`os.execvp` to execute the child program. *args* should normally be a |
Nick Coghlan | 7dfc9e1 | 2010-02-04 12:43:58 +0000 | [diff] [blame] | 259 | sequence. If a string is specified for *args*, it will be used as the name |
| 260 | or path of the program to execute; this will only work if the program is |
| 261 | being given no arguments. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 262 | |
Nick Coghlan | 7dfc9e1 | 2010-02-04 12:43:58 +0000 | [diff] [blame] | 263 | .. note:: |
| 264 | |
| 265 | :meth:`shlex.split` can be useful when determining the correct |
| 266 | tokenization for *args*, especially in complex cases:: |
| 267 | |
| 268 | >>> import shlex, subprocess |
| 269 | >>> command_line = raw_input() |
| 270 | /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'" |
| 271 | >>> args = shlex.split(command_line) |
| 272 | >>> print args |
| 273 | ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"] |
| 274 | >>> p = subprocess.Popen(args) # Success! |
| 275 | |
| 276 | Note in particular that options (such as *-input*) and arguments (such |
| 277 | as *eggs.txt*) that are separated by whitespace in the shell go in separate |
| 278 | list elements, while arguments that need quoting or backslash escaping when |
| 279 | used in the shell (such as filenames containing spaces or the *echo* command |
| 280 | shown above) are single list elements. |
| 281 | |
| 282 | On Unix, with *shell=True*: If args is a string, it specifies the command |
| 283 | string to execute through the shell. This means that the string must be |
| 284 | formatted exactly as it would be when typed at the shell prompt. This |
| 285 | includes, for example, quoting or backslash escaping filenames with spaces in |
| 286 | them. If *args* is a sequence, the first item specifies the command string, and |
| 287 | any additional items will be treated as additional arguments to the shell |
| 288 | itself. That is to say, *Popen* does the equivalent of:: |
| 289 | |
| 290 | Popen(['/bin/sh', '-c', args[0], args[1], ...]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 291 | |
| 292 | On Windows: the :class:`Popen` class uses CreateProcess() to execute the child |
Eli Bendersky | 929e276 | 2011-04-15 07:35:06 +0300 | [diff] [blame] | 293 | child program, which operates on strings. If *args* is a sequence, it will |
| 294 | be converted to a string in a manner described in |
| 295 | :ref:`converting-argument-sequence`. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 296 | |
| 297 | *bufsize*, if given, has the same meaning as the corresponding argument to the |
| 298 | built-in open() function: :const:`0` means unbuffered, :const:`1` means line |
| 299 | buffered, any other positive value means use a buffer of (approximately) that |
| 300 | size. A negative *bufsize* means to use the system default, which usually means |
| 301 | fully buffered. The default value for *bufsize* is :const:`0` (unbuffered). |
| 302 | |
Antoine Pitrou | c395545 | 2010-06-02 17:08:47 +0000 | [diff] [blame] | 303 | .. note:: |
| 304 | |
| 305 | If you experience performance issues, it is recommended that you try to |
| 306 | enable buffering by setting *bufsize* to either -1 or a large enough |
| 307 | positive value (such as 4096). |
| 308 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 309 | The *executable* argument specifies the program to execute. It is very seldom |
| 310 | needed: Usually, the program to execute is defined by the *args* argument. If |
| 311 | ``shell=True``, the *executable* argument specifies which shell to use. On Unix, |
| 312 | the default shell is :file:`/bin/sh`. On Windows, the default shell is |
Georg Brandl | 0d8649a | 2009-06-30 16:17:28 +0000 | [diff] [blame] | 313 | specified by the :envvar:`COMSPEC` environment variable. The only reason you |
| 314 | would need to specify ``shell=True`` on Windows is where the command you |
| 315 | wish to execute is actually built in to the shell, eg ``dir``, ``copy``. |
| 316 | You don't need ``shell=True`` to run a batch file, nor to run a console-based |
| 317 | executable. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 318 | |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 319 | *stdin*, *stdout* and *stderr* specify the executed program's standard input, |
Georg Brandl | f5d5a66 | 2008-12-06 11:57:12 +0000 | [diff] [blame] | 320 | standard output and standard error file handles, respectively. Valid values |
| 321 | are :data:`PIPE`, an existing file descriptor (a positive integer), an |
| 322 | existing file object, and ``None``. :data:`PIPE` indicates that a new pipe |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 323 | to the child should be created. With the default settings of ``None``, no |
| 324 | redirection will occur; the child's file handles will be inherited from the |
| 325 | parent. Additionally, *stderr* can be :data:`STDOUT`, which indicates that |
| 326 | the stderr data from the child process should be captured into the same file |
| 327 | handle as for stdout. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 328 | |
| 329 | If *preexec_fn* is set to a callable object, this object will be called in the |
| 330 | child process just before the child is executed. (Unix only) |
| 331 | |
| 332 | If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and |
| 333 | :const:`2` will be closed before the child process is executed. (Unix only). |
| 334 | Or, on Windows, if *close_fds* is true then no handles will be inherited by the |
| 335 | child process. Note that on Windows, you cannot set *close_fds* to true and |
| 336 | also redirect the standard handles by setting *stdin*, *stdout* or *stderr*. |
| 337 | |
| 338 | If *shell* is :const:`True`, the specified command will be executed through the |
| 339 | shell. |
| 340 | |
Nick Coghlan | 87ba642 | 2011-10-27 17:55:13 +1000 | [diff] [blame] | 341 | .. warning:: |
Nick Coghlan | 65ad31a | 2011-10-26 21:15:53 +1000 | [diff] [blame] | 342 | |
| 343 | Enabling this option can be a security hazard if combined with untrusted |
| 344 | input. See the warning under :ref:`frequently-used-arguments` |
| 345 | for details. |
| 346 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 347 | If *cwd* is not ``None``, the child's current directory will be changed to *cwd* |
| 348 | before it is executed. Note that this directory is not considered when |
| 349 | searching the executable, so you can't specify the program's path relative to |
| 350 | *cwd*. |
| 351 | |
Georg Brandl | f801b0f | 2008-04-19 16:58:49 +0000 | [diff] [blame] | 352 | If *env* is not ``None``, it must be a mapping that defines the environment |
| 353 | variables for the new process; these are used instead of inheriting the current |
| 354 | process' environment, which is the default behavior. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 355 | |
R. David Murray | 7203081 | 2009-04-16 18:12:53 +0000 | [diff] [blame] | 356 | .. note:: |
R. David Murray | 6076d39 | 2009-04-15 22:33:07 +0000 | [diff] [blame] | 357 | |
R. David Murray | 7203081 | 2009-04-16 18:12:53 +0000 | [diff] [blame] | 358 | If specified, *env* must provide any variables required |
| 359 | for the program to execute. On Windows, in order to run a |
| 360 | `side-by-side assembly`_ the specified *env* **must** include a valid |
R. David Murray | 6076d39 | 2009-04-15 22:33:07 +0000 | [diff] [blame] | 361 | :envvar:`SystemRoot`. |
| 362 | |
R. David Murray | 7203081 | 2009-04-16 18:12:53 +0000 | [diff] [blame] | 363 | .. _side-by-side assembly: http://en.wikipedia.org/wiki/Side-by-Side_Assembly |
| 364 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 365 | If *universal_newlines* is :const:`True`, the file objects stdout and stderr are |
| 366 | opened as text files, but lines may be terminated by any of ``'\n'``, the Unix |
Georg Brandl | 9af9498 | 2008-09-13 17:41:16 +0000 | [diff] [blame] | 367 | end-of-line convention, ``'\r'``, the old Macintosh convention or ``'\r\n'``, the |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 368 | Windows convention. All of these external representations are seen as ``'\n'`` |
| 369 | by the Python program. |
| 370 | |
| 371 | .. note:: |
| 372 | |
Georg Brandl | 6ab5d08 | 2009-12-20 14:33:20 +0000 | [diff] [blame] | 373 | This feature is only available if Python is built with universal newline |
| 374 | support (the default). Also, the newlines attribute of the file objects |
| 375 | :attr:`stdout`, :attr:`stdin` and :attr:`stderr` are not updated by the |
| 376 | communicate() method. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 377 | |
Brian Curtin | bb23bd6 | 2011-04-29 22:23:46 -0500 | [diff] [blame] | 378 | If given, *startupinfo* will be a :class:`STARTUPINFO` object, which is |
| 379 | passed to the underlying ``CreateProcess`` function. |
| 380 | *creationflags*, if given, can be :data:`CREATE_NEW_CONSOLE` or |
| 381 | :data:`CREATE_NEW_PROCESS_GROUP`. (Windows only) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 382 | |
| 383 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 384 | Exceptions |
| 385 | ^^^^^^^^^^ |
| 386 | |
| 387 | Exceptions raised in the child process, before the new program has started to |
| 388 | execute, will be re-raised in the parent. Additionally, the exception object |
| 389 | will have one extra attribute called :attr:`child_traceback`, which is a string |
Georg Brandl | 21946af | 2010-10-06 09:28:45 +0000 | [diff] [blame] | 390 | containing traceback information from the child's point of view. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 391 | |
| 392 | The most common exception raised is :exc:`OSError`. This occurs, for example, |
| 393 | when trying to execute a non-existent file. Applications should prepare for |
| 394 | :exc:`OSError` exceptions. |
| 395 | |
| 396 | A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid |
| 397 | arguments. |
| 398 | |
Nick Coghlan | 2ed203a | 2011-10-26 21:05:56 +1000 | [diff] [blame] | 399 | :func:`check_call` and :func:`check_output` will raise |
| 400 | :exc:`CalledProcessError` if the called process returns a non-zero return |
| 401 | code. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 402 | |
| 403 | |
| 404 | Security |
| 405 | ^^^^^^^^ |
| 406 | |
Nick Coghlan | 2ed203a | 2011-10-26 21:05:56 +1000 | [diff] [blame] | 407 | Unlike some other popen functions, this implementation will never call a |
| 408 | system shell implicitly. This means that all characters, including shell |
| 409 | metacharacters, can safely be passed to child processes. Obviously, if the |
| 410 | shell is invoked explicitly, then it is the application's responsibility to |
Nick Coghlan | 63c54e8 | 2011-10-26 21:34:26 +1000 | [diff] [blame] | 411 | ensure that all whitespace and metacharacters are quoted appropriately. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 412 | |
| 413 | |
| 414 | Popen Objects |
| 415 | ------------- |
| 416 | |
| 417 | Instances of the :class:`Popen` class have the following methods: |
| 418 | |
| 419 | |
| 420 | .. method:: Popen.poll() |
| 421 | |
Georg Brandl | 2cb103f | 2008-01-06 16:01:26 +0000 | [diff] [blame] | 422 | Check if child process has terminated. Set and return :attr:`returncode` |
| 423 | attribute. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 424 | |
| 425 | |
| 426 | .. method:: Popen.wait() |
| 427 | |
Georg Brandl | 2cb103f | 2008-01-06 16:01:26 +0000 | [diff] [blame] | 428 | Wait for child process to terminate. Set and return :attr:`returncode` |
| 429 | attribute. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 430 | |
Georg Brandl | 143de62 | 2008-08-04 06:29:36 +0000 | [diff] [blame] | 431 | .. warning:: |
| 432 | |
Philip Jenvey | 2627553 | 2009-12-03 02:25:54 +0000 | [diff] [blame] | 433 | This will deadlock when using ``stdout=PIPE`` and/or |
| 434 | ``stderr=PIPE`` and the child process generates enough output to |
| 435 | a pipe such that it blocks waiting for the OS pipe buffer to |
| 436 | accept more data. Use :meth:`communicate` to avoid that. |
Gregory P. Smith | 0879250 | 2008-08-04 01:03:50 +0000 | [diff] [blame] | 437 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 438 | |
| 439 | .. method:: Popen.communicate(input=None) |
| 440 | |
| 441 | Interact with process: Send data to stdin. Read data from stdout and stderr, |
| 442 | until end-of-file is reached. Wait for process to terminate. The optional |
| 443 | *input* argument should be a string to be sent to the child process, or |
| 444 | ``None``, if no data should be sent to the child. |
| 445 | |
Georg Brandl | 1743201 | 2008-12-04 21:28:16 +0000 | [diff] [blame] | 446 | :meth:`communicate` returns a tuple ``(stdoutdata, stderrdata)``. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 447 | |
Georg Brandl | 439f250 | 2007-11-24 11:31:46 +0000 | [diff] [blame] | 448 | Note that if you want to send data to the process's stdin, you need to create |
| 449 | the Popen object with ``stdin=PIPE``. Similarly, to get anything other than |
| 450 | ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or |
| 451 | ``stderr=PIPE`` too. |
| 452 | |
Georg Brandl | 2cb103f | 2008-01-06 16:01:26 +0000 | [diff] [blame] | 453 | .. note:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 454 | |
Georg Brandl | 2cb103f | 2008-01-06 16:01:26 +0000 | [diff] [blame] | 455 | The data read is buffered in memory, so do not use this method if the data |
| 456 | size is large or unlimited. |
| 457 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 458 | |
Christian Heimes | e74c8f2 | 2008-04-19 02:23:57 +0000 | [diff] [blame] | 459 | .. method:: Popen.send_signal(signal) |
| 460 | |
| 461 | Sends the signal *signal* to the child. |
| 462 | |
| 463 | .. note:: |
| 464 | |
Brian Curtin | e5aa886 | 2010-04-02 23:26:06 +0000 | [diff] [blame] | 465 | On Windows, SIGTERM is an alias for :meth:`terminate`. CTRL_C_EVENT and |
Ezio Melotti | 9ccc581 | 2010-04-05 08:16:41 +0000 | [diff] [blame] | 466 | CTRL_BREAK_EVENT can be sent to processes started with a *creationflags* |
Brian Curtin | e5aa886 | 2010-04-02 23:26:06 +0000 | [diff] [blame] | 467 | parameter which includes `CREATE_NEW_PROCESS_GROUP`. |
Georg Brandl | 734de68 | 2008-04-19 08:23:59 +0000 | [diff] [blame] | 468 | |
| 469 | .. versionadded:: 2.6 |
Christian Heimes | e74c8f2 | 2008-04-19 02:23:57 +0000 | [diff] [blame] | 470 | |
| 471 | |
| 472 | .. method:: Popen.terminate() |
| 473 | |
| 474 | Stop the child. On Posix OSs the method sends SIGTERM to the |
Andrew M. Kuchling | 64c6a0e | 2008-04-21 02:08:00 +0000 | [diff] [blame] | 475 | child. On Windows the Win32 API function :cfunc:`TerminateProcess` is called |
Christian Heimes | e74c8f2 | 2008-04-19 02:23:57 +0000 | [diff] [blame] | 476 | to stop the child. |
| 477 | |
Georg Brandl | 734de68 | 2008-04-19 08:23:59 +0000 | [diff] [blame] | 478 | .. versionadded:: 2.6 |
| 479 | |
Christian Heimes | e74c8f2 | 2008-04-19 02:23:57 +0000 | [diff] [blame] | 480 | |
| 481 | .. method:: Popen.kill() |
| 482 | |
| 483 | Kills the child. On Posix OSs the function sends SIGKILL to the child. |
Georg Brandl | 734de68 | 2008-04-19 08:23:59 +0000 | [diff] [blame] | 484 | On Windows :meth:`kill` is an alias for :meth:`terminate`. |
| 485 | |
| 486 | .. versionadded:: 2.6 |
Christian Heimes | e74c8f2 | 2008-04-19 02:23:57 +0000 | [diff] [blame] | 487 | |
| 488 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 489 | The following attributes are also available: |
| 490 | |
Georg Brandl | 143de62 | 2008-08-04 06:29:36 +0000 | [diff] [blame] | 491 | .. warning:: |
| 492 | |
Georg Brandl | 16a57f6 | 2009-04-27 15:29:09 +0000 | [diff] [blame] | 493 | Use :meth:`communicate` rather than :attr:`.stdin.write <stdin>`, |
| 494 | :attr:`.stdout.read <stdout>` or :attr:`.stderr.read <stderr>` to avoid |
| 495 | deadlocks due to any of the other OS pipe buffers filling up and blocking the |
| 496 | child process. |
Georg Brandl | 143de62 | 2008-08-04 06:29:36 +0000 | [diff] [blame] | 497 | |
| 498 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 499 | .. attribute:: Popen.stdin |
| 500 | |
Georg Brandl | f5d5a66 | 2008-12-06 11:57:12 +0000 | [diff] [blame] | 501 | If the *stdin* argument was :data:`PIPE`, this attribute is a file object |
| 502 | that provides input to the child process. Otherwise, it is ``None``. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 503 | |
| 504 | |
| 505 | .. attribute:: Popen.stdout |
| 506 | |
Georg Brandl | f5d5a66 | 2008-12-06 11:57:12 +0000 | [diff] [blame] | 507 | If the *stdout* argument was :data:`PIPE`, this attribute is a file object |
| 508 | that provides output from the child process. Otherwise, it is ``None``. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 509 | |
| 510 | |
| 511 | .. attribute:: Popen.stderr |
| 512 | |
Georg Brandl | f5d5a66 | 2008-12-06 11:57:12 +0000 | [diff] [blame] | 513 | If the *stderr* argument was :data:`PIPE`, this attribute is a file object |
| 514 | that provides error output from the child process. Otherwise, it is |
| 515 | ``None``. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 516 | |
| 517 | |
| 518 | .. attribute:: Popen.pid |
| 519 | |
| 520 | The process ID of the child process. |
| 521 | |
Georg Brandl | 0b56ce0 | 2010-03-21 09:28:16 +0000 | [diff] [blame] | 522 | Note that if you set the *shell* argument to ``True``, this is the process ID |
| 523 | of the spawned shell. |
| 524 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 525 | |
| 526 | .. attribute:: Popen.returncode |
| 527 | |
Georg Brandl | 2cb103f | 2008-01-06 16:01:26 +0000 | [diff] [blame] | 528 | The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly |
| 529 | by :meth:`communicate`). A ``None`` value indicates that the process |
| 530 | hasn't terminated yet. |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 531 | |
Georg Brandl | 2cb103f | 2008-01-06 16:01:26 +0000 | [diff] [blame] | 532 | A negative value ``-N`` indicates that the child was terminated by signal |
| 533 | ``N`` (Unix only). |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 534 | |
| 535 | |
Brian Curtin | bb23bd6 | 2011-04-29 22:23:46 -0500 | [diff] [blame] | 536 | Windows Popen Helpers |
| 537 | --------------------- |
| 538 | |
| 539 | The :class:`STARTUPINFO` class and following constants are only available |
| 540 | on Windows. |
| 541 | |
| 542 | .. class:: STARTUPINFO() |
| 543 | |
| 544 | Partial support of the Windows |
| 545 | `STARTUPINFO <http://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx>`__ |
| 546 | structure is used for :class:`Popen` creation. |
| 547 | |
| 548 | .. attribute:: dwFlags |
| 549 | |
Senthil Kumaran | 6f18b98 | 2011-07-04 12:50:02 -0700 | [diff] [blame] | 550 | A bit field that determines whether certain :class:`STARTUPINFO` |
| 551 | attributes are used when the process creates a window. :: |
Brian Curtin | bb23bd6 | 2011-04-29 22:23:46 -0500 | [diff] [blame] | 552 | |
| 553 | si = subprocess.STARTUPINFO() |
| 554 | si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW |
| 555 | |
| 556 | .. attribute:: hStdInput |
| 557 | |
Senthil Kumaran | 6f18b98 | 2011-07-04 12:50:02 -0700 | [diff] [blame] | 558 | If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute |
| 559 | is the standard input handle for the process. If |
| 560 | :data:`STARTF_USESTDHANDLES` is not specified, the default for standard |
| 561 | input is the keyboard buffer. |
Brian Curtin | bb23bd6 | 2011-04-29 22:23:46 -0500 | [diff] [blame] | 562 | |
| 563 | .. attribute:: hStdOutput |
| 564 | |
Senthil Kumaran | 6f18b98 | 2011-07-04 12:50:02 -0700 | [diff] [blame] | 565 | If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute |
| 566 | is the standard output handle for the process. Otherwise, this attribute |
| 567 | is ignored and the default for standard output is the console window's |
Brian Curtin | bb23bd6 | 2011-04-29 22:23:46 -0500 | [diff] [blame] | 568 | buffer. |
| 569 | |
| 570 | .. attribute:: hStdError |
| 571 | |
Senthil Kumaran | 6f18b98 | 2011-07-04 12:50:02 -0700 | [diff] [blame] | 572 | If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute |
| 573 | is the standard error handle for the process. Otherwise, this attribute is |
Brian Curtin | bb23bd6 | 2011-04-29 22:23:46 -0500 | [diff] [blame] | 574 | ignored and the default for standard error is the console window's buffer. |
| 575 | |
| 576 | .. attribute:: wShowWindow |
| 577 | |
Senthil Kumaran | 6f18b98 | 2011-07-04 12:50:02 -0700 | [diff] [blame] | 578 | If :attr:`dwFlags` specifies :data:`STARTF_USESHOWWINDOW`, this attribute |
Brian Curtin | bb23bd6 | 2011-04-29 22:23:46 -0500 | [diff] [blame] | 579 | can be any of the values that can be specified in the ``nCmdShow`` |
| 580 | parameter for the |
| 581 | `ShowWindow <http://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx>`__ |
Senthil Kumaran | 6f18b98 | 2011-07-04 12:50:02 -0700 | [diff] [blame] | 582 | function, except for ``SW_SHOWDEFAULT``. Otherwise, this attribute is |
Brian Curtin | bb23bd6 | 2011-04-29 22:23:46 -0500 | [diff] [blame] | 583 | ignored. |
| 584 | |
| 585 | :data:`SW_HIDE` is provided for this attribute. It is used when |
| 586 | :class:`Popen` is called with ``shell=True``. |
| 587 | |
| 588 | |
| 589 | Constants |
| 590 | ^^^^^^^^^ |
| 591 | |
| 592 | The :mod:`subprocess` module exposes the following constants. |
| 593 | |
| 594 | .. data:: STD_INPUT_HANDLE |
| 595 | |
| 596 | The standard input device. Initially, this is the console input buffer, |
| 597 | ``CONIN$``. |
| 598 | |
| 599 | .. data:: STD_OUTPUT_HANDLE |
| 600 | |
| 601 | The standard output device. Initially, this is the active console screen |
| 602 | buffer, ``CONOUT$``. |
| 603 | |
| 604 | .. data:: STD_ERROR_HANDLE |
| 605 | |
| 606 | The standard error device. Initially, this is the active console screen |
| 607 | buffer, ``CONOUT$``. |
| 608 | |
| 609 | .. data:: SW_HIDE |
| 610 | |
| 611 | Hides the window. Another window will be activated. |
| 612 | |
| 613 | .. data:: STARTF_USESTDHANDLES |
| 614 | |
| 615 | Specifies that the :attr:`STARTUPINFO.hStdInput`, |
Senthil Kumaran | 6f18b98 | 2011-07-04 12:50:02 -0700 | [diff] [blame] | 616 | :attr:`STARTUPINFO.hStdOutput`, and :attr:`STARTUPINFO.hStdError` attributes |
Brian Curtin | bb23bd6 | 2011-04-29 22:23:46 -0500 | [diff] [blame] | 617 | contain additional information. |
| 618 | |
| 619 | .. data:: STARTF_USESHOWWINDOW |
| 620 | |
Senthil Kumaran | 6f18b98 | 2011-07-04 12:50:02 -0700 | [diff] [blame] | 621 | Specifies that the :attr:`STARTUPINFO.wShowWindow` attribute contains |
Brian Curtin | bb23bd6 | 2011-04-29 22:23:46 -0500 | [diff] [blame] | 622 | additional information. |
| 623 | |
| 624 | .. data:: CREATE_NEW_CONSOLE |
| 625 | |
| 626 | The new process has a new console, instead of inheriting its parent's |
| 627 | console (the default). |
| 628 | |
| 629 | This flag is always set when :class:`Popen` is created with ``shell=True``. |
| 630 | |
| 631 | .. data:: CREATE_NEW_PROCESS_GROUP |
| 632 | |
| 633 | A :class:`Popen` ``creationflags`` parameter to specify that a new process |
| 634 | group will be created. This flag is necessary for using :func:`os.kill` |
| 635 | on the subprocess. |
| 636 | |
| 637 | This flag is ignored if :data:`CREATE_NEW_CONSOLE` is specified. |
| 638 | |
| 639 | |
Georg Brandl | 0ba92b2 | 2008-06-22 09:05:29 +0000 | [diff] [blame] | 640 | .. _subprocess-replacements: |
| 641 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 642 | Replacing Older Functions with the subprocess Module |
| 643 | ---------------------------------------------------- |
| 644 | |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 645 | In this section, "a becomes b" means that b can be used as a replacement for a. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 646 | |
| 647 | .. note:: |
| 648 | |
Nick Coghlan | 2ed203a | 2011-10-26 21:05:56 +1000 | [diff] [blame] | 649 | All "a" functions in this section fail (more or less) silently if the |
| 650 | executed program cannot be found; the "b" replacements raise :exc:`OSError` |
| 651 | instead. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 652 | |
Nick Coghlan | 2ed203a | 2011-10-26 21:05:56 +1000 | [diff] [blame] | 653 | In addition, the replacements using :func:`check_output` will fail with a |
| 654 | :exc:`CalledProcessError` if the requested operation produces a non-zero |
| 655 | return code. The output is still available as the ``output`` attribute of |
| 656 | the raised exception. |
| 657 | |
| 658 | In the following examples, we assume that the relevant functions have already |
| 659 | been imported from the subprocess module. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 660 | |
| 661 | |
| 662 | Replacing /bin/sh shell backquote |
| 663 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 664 | |
| 665 | :: |
| 666 | |
| 667 | output=`mycmd myarg` |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 668 | # becomes |
| 669 | output = check_output(["mycmd", "myarg"]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 670 | |
| 671 | |
Benjamin Peterson | cae5848 | 2008-10-10 20:38:49 +0000 | [diff] [blame] | 672 | Replacing shell pipeline |
| 673 | ^^^^^^^^^^^^^^^^^^^^^^^^ |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 674 | |
| 675 | :: |
| 676 | |
| 677 | output=`dmesg | grep hda` |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 678 | # becomes |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 679 | p1 = Popen(["dmesg"], stdout=PIPE) |
| 680 | p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) |
Gregory P. Smith | e3e967f | 2011-02-05 21:49:56 +0000 | [diff] [blame] | 681 | p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 682 | output = p2.communicate()[0] |
| 683 | |
Gregory P. Smith | e3e967f | 2011-02-05 21:49:56 +0000 | [diff] [blame] | 684 | The p1.stdout.close() call after starting the p2 is important in order for p1 |
| 685 | to receive a SIGPIPE if p2 exits before p1. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 686 | |
Nick Coghlan | 2ed203a | 2011-10-26 21:05:56 +1000 | [diff] [blame] | 687 | Alternatively, for trusted input, the shell's own pipeline support may still |
| 688 | be used directly: |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 689 | |
| 690 | output=`dmesg | grep hda` |
| 691 | # becomes |
| 692 | output=check_output("dmesg | grep hda", shell=True) |
| 693 | |
| 694 | |
R. David Murray | ccb9d4b | 2009-06-09 00:44:22 +0000 | [diff] [blame] | 695 | Replacing :func:`os.system` |
| 696 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 697 | |
| 698 | :: |
| 699 | |
| 700 | sts = os.system("mycmd" + " myarg") |
Nick Coghlan | 8671157 | 2011-10-24 22:19:40 +1000 | [diff] [blame] | 701 | # becomes |
| 702 | sts = call("mycmd" + " myarg", shell=True) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 703 | |
| 704 | Notes: |
| 705 | |
| 706 | * Calling the program through the shell is usually not required. |
| 707 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 708 | A more realistic example would look like this:: |
| 709 | |
| 710 | try: |
| 711 | retcode = call("mycmd" + " myarg", shell=True) |
| 712 | if retcode < 0: |
| 713 | print >>sys.stderr, "Child was terminated by signal", -retcode |
| 714 | else: |
| 715 | print >>sys.stderr, "Child returned", retcode |
| 716 | except OSError, e: |
| 717 | print >>sys.stderr, "Execution failed:", e |
| 718 | |
| 719 | |
R. David Murray | ccb9d4b | 2009-06-09 00:44:22 +0000 | [diff] [blame] | 720 | Replacing the :func:`os.spawn <os.spawnl>` family |
| 721 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 722 | |
| 723 | P_NOWAIT example:: |
| 724 | |
| 725 | pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") |
| 726 | ==> |
| 727 | pid = Popen(["/bin/mycmd", "myarg"]).pid |
| 728 | |
| 729 | P_WAIT example:: |
| 730 | |
| 731 | retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg") |
| 732 | ==> |
| 733 | retcode = call(["/bin/mycmd", "myarg"]) |
| 734 | |
| 735 | Vector example:: |
| 736 | |
| 737 | os.spawnvp(os.P_NOWAIT, path, args) |
| 738 | ==> |
| 739 | Popen([path] + args[1:]) |
| 740 | |
| 741 | Environment example:: |
| 742 | |
| 743 | os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env) |
| 744 | ==> |
| 745 | Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}) |
| 746 | |
| 747 | |
R. David Murray | ccb9d4b | 2009-06-09 00:44:22 +0000 | [diff] [blame] | 748 | Replacing :func:`os.popen`, :func:`os.popen2`, :func:`os.popen3` |
| 749 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 750 | |
| 751 | :: |
| 752 | |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 753 | pipe = os.popen("cmd", 'r', bufsize) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 754 | ==> |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 755 | pipe = Popen("cmd", shell=True, bufsize=bufsize, stdout=PIPE).stdout |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 756 | |
| 757 | :: |
| 758 | |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 759 | pipe = os.popen("cmd", 'w', bufsize) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 760 | ==> |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 761 | pipe = Popen("cmd", shell=True, bufsize=bufsize, stdin=PIPE).stdin |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 762 | |
| 763 | :: |
| 764 | |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 765 | (child_stdin, child_stdout) = os.popen2("cmd", mode, bufsize) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 766 | ==> |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 767 | p = Popen("cmd", shell=True, bufsize=bufsize, |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 768 | stdin=PIPE, stdout=PIPE, close_fds=True) |
| 769 | (child_stdin, child_stdout) = (p.stdin, p.stdout) |
| 770 | |
| 771 | :: |
| 772 | |
| 773 | (child_stdin, |
| 774 | child_stdout, |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 775 | child_stderr) = os.popen3("cmd", mode, bufsize) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 776 | ==> |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 777 | p = Popen("cmd", shell=True, bufsize=bufsize, |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 778 | stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) |
| 779 | (child_stdin, |
| 780 | child_stdout, |
| 781 | child_stderr) = (p.stdin, p.stdout, p.stderr) |
| 782 | |
| 783 | :: |
| 784 | |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 785 | (child_stdin, child_stdout_and_stderr) = os.popen4("cmd", mode, |
| 786 | bufsize) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 787 | ==> |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 788 | p = Popen("cmd", shell=True, bufsize=bufsize, |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 789 | stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) |
| 790 | (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout) |
| 791 | |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 792 | On Unix, os.popen2, os.popen3 and os.popen4 also accept a sequence as |
| 793 | the command to execute, in which case arguments will be passed |
| 794 | directly to the program without shell intervention. This usage can be |
| 795 | replaced as follows:: |
| 796 | |
| 797 | (child_stdin, child_stdout) = os.popen2(["/bin/ls", "-l"], mode, |
| 798 | bufsize) |
| 799 | ==> |
| 800 | p = Popen(["/bin/ls", "-l"], bufsize=bufsize, stdin=PIPE, stdout=PIPE) |
| 801 | (child_stdin, child_stdout) = (p.stdin, p.stdout) |
| 802 | |
R. David Murray | ccb9d4b | 2009-06-09 00:44:22 +0000 | [diff] [blame] | 803 | Return code handling translates as follows:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 804 | |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 805 | pipe = os.popen("cmd", 'w') |
R. David Murray | ccb9d4b | 2009-06-09 00:44:22 +0000 | [diff] [blame] | 806 | ... |
| 807 | rc = pipe.close() |
Stefan Krah | a253dc1 | 2010-07-14 10:06:07 +0000 | [diff] [blame] | 808 | if rc is not None and rc >> 8: |
R. David Murray | ccb9d4b | 2009-06-09 00:44:22 +0000 | [diff] [blame] | 809 | print "There were some errors" |
| 810 | ==> |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 811 | process = Popen("cmd", 'w', shell=True, stdin=PIPE) |
R. David Murray | ccb9d4b | 2009-06-09 00:44:22 +0000 | [diff] [blame] | 812 | ... |
| 813 | process.stdin.close() |
| 814 | if process.wait() != 0: |
| 815 | print "There were some errors" |
| 816 | |
| 817 | |
| 818 | Replacing functions from the :mod:`popen2` module |
| 819 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 820 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 821 | :: |
| 822 | |
| 823 | (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode) |
| 824 | ==> |
| 825 | p = Popen(["somestring"], shell=True, bufsize=bufsize, |
| 826 | stdin=PIPE, stdout=PIPE, close_fds=True) |
| 827 | (child_stdout, child_stdin) = (p.stdout, p.stdin) |
| 828 | |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 829 | On Unix, popen2 also accepts a sequence as the command to execute, in |
| 830 | which case arguments will be passed directly to the program without |
| 831 | shell intervention. This usage can be replaced as follows:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 832 | |
Philip Jenvey | 8b90204 | 2009-09-29 19:10:15 +0000 | [diff] [blame] | 833 | (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, |
| 834 | mode) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 835 | ==> |
| 836 | p = Popen(["mycmd", "myarg"], bufsize=bufsize, |
| 837 | stdin=PIPE, stdout=PIPE, close_fds=True) |
| 838 | (child_stdout, child_stdin) = (p.stdout, p.stdin) |
| 839 | |
Georg Brandl | f5d5a66 | 2008-12-06 11:57:12 +0000 | [diff] [blame] | 840 | :class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as |
| 841 | :class:`subprocess.Popen`, except that: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 842 | |
Georg Brandl | f5d5a66 | 2008-12-06 11:57:12 +0000 | [diff] [blame] | 843 | * :class:`Popen` raises an exception if the execution fails. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 844 | |
| 845 | * the *capturestderr* argument is replaced with the *stderr* argument. |
| 846 | |
Georg Brandl | f5d5a66 | 2008-12-06 11:57:12 +0000 | [diff] [blame] | 847 | * ``stdin=PIPE`` and ``stdout=PIPE`` must be specified. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 848 | |
| 849 | * popen2 closes all file descriptors by default, but you have to specify |
Georg Brandl | f5d5a66 | 2008-12-06 11:57:12 +0000 | [diff] [blame] | 850 | ``close_fds=True`` with :class:`Popen`. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 851 | |
Nick Coghlan | 2ed203a | 2011-10-26 21:05:56 +1000 | [diff] [blame] | 852 | |
Eli Bendersky | 929e276 | 2011-04-15 07:35:06 +0300 | [diff] [blame] | 853 | Notes |
| 854 | ----- |
| 855 | |
| 856 | .. _converting-argument-sequence: |
| 857 | |
| 858 | Converting an argument sequence to a string on Windows |
| 859 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 860 | |
| 861 | On Windows, an *args* sequence is converted to a string that can be parsed |
| 862 | using the following rules (which correspond to the rules used by the MS C |
| 863 | runtime): |
| 864 | |
| 865 | 1. Arguments are delimited by white space, which is either a |
| 866 | space or a tab. |
| 867 | |
| 868 | 2. A string surrounded by double quotation marks is |
| 869 | interpreted as a single argument, regardless of white space |
| 870 | contained within. A quoted string can be embedded in an |
| 871 | argument. |
| 872 | |
| 873 | 3. A double quotation mark preceded by a backslash is |
| 874 | interpreted as a literal double quotation mark. |
| 875 | |
| 876 | 4. Backslashes are interpreted literally, unless they |
| 877 | immediately precede a double quotation mark. |
| 878 | |
| 879 | 5. If backslashes immediately precede a double quotation mark, |
| 880 | every pair of backslashes is interpreted as a literal |
| 881 | backslash. If the number of backslashes is odd, the last |
| 882 | backslash escapes the next double quotation mark as |
| 883 | described in rule 3. |
| 884 | |