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