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