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