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