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