Changeset 391 for python/trunk/Doc/library/subprocess.rst
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Doc/library/subprocess.rst
r2 r391 31 31 32 32 33 Using the subprocess Module 34 --------------------------- 35 36 This module defines one class called :class:`Popen`: 37 38 39 .. class:: Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0) 40 41 Arguments are: 42 43 *args* should be a string, or a sequence of program arguments. The program 44 to execute is normally the first item in the args sequence or the string if 45 a string is given, but can be explicitly set by using the *executable* 46 argument. When *executable* is given, the first item in the args sequence 47 is still treated by most programs as the command name, which can then be 48 different from the actual executable name. On Unix, it becomes the display 49 name for the executing program in utilities such as :program:`ps`. 50 51 On Unix, with *shell=False* (default): In this case, the Popen class uses 52 :meth:`os.execvp` to execute the child program. *args* should normally be a 53 sequence. If a string is specified for *args*, it will be used as the name 54 or path of the program to execute; this will only work if the program is 55 being given no arguments. 33 Using the :mod:`subprocess` Module 34 ---------------------------------- 35 36 The recommended approach to invoking subprocesses is to use the following 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. 39 40 41 .. function:: call(args, *, stdin=None, stdout=None, stderr=None, shell=False) 42 43 Run the command described by *args*. Wait for command to complete, then 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 49 that of the :class:`Popen` constructor - this functions passes all 50 supplied arguments directly through to that interface. 51 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 64 :ref:`frequently-used-arguments` for details. 65 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. 56 300 57 301 .. note:: … … 74 318 shown above) are single list elements. 75 319 76 On Unix, with *shell=True*: If args is a string, it specifies the command 77 string to execute through the shell. This means that the string must be 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 329 *args* is a string, the string specifies the command 330 to execute through the shell. This means that the string must be 78 331 formatted exactly as it would be when typed at the shell prompt. This 79 332 includes, for example, quoting or backslash escaping filenames with spaces in 80 333 them. If *args* is a sequence, the first item specifies the command string, and 81 334 any additional items will be treated as additional arguments to the shell 82 itself. That is to say, *Popen*does the equivalent of::335 itself. That is to say, :class:`Popen` does the equivalent of:: 83 336 84 337 Popen(['/bin/sh', '-c', args[0], args[1], ...]) 85 338 86 On Windows: the :class:`Popen` class uses CreateProcess() to execute the child 87 program, which operates on strings. If *args* is a sequence, it will be 88 converted to a string using the :meth:`list2cmdline` method. Please note that 89 not all MS Windows applications interpret the command line the same way: 90 :meth:`list2cmdline` is designed for applications using the same rules as the MS 91 C runtime. 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 342 into the shell (e.g. :command:`dir` or :command:`copy`). You do not need 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` 349 for details. 92 350 93 351 *bufsize*, if given, has the same meaning as the corresponding argument to the … … 97 355 fully buffered. The default value for *bufsize* is :const:`0` (unbuffered). 98 356 99 The *executable* argument specifies the program to execute. It is very seldom 100 needed: Usually, the program to execute is defined by the *args* argument. If 101 ``shell=True``, the *executable* argument specifies which shell to use. On Unix, 102 the default shell is :file:`/bin/sh`. On Windows, the default shell is 103 specified by the :envvar:`COMSPEC` environment variable. The only reason you 104 would need to specify ``shell=True`` on Windows is where the command you 105 wish to execute is actually built in to the shell, eg ``dir``, ``copy``. 106 You don't need ``shell=True`` to run a batch file, nor to run a console-based 107 executable. 108 109 *stdin*, *stdout* and *stderr* specify the executed programs' standard input, 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`. 372 373 *stdin*, *stdout* and *stderr* specify the executed program's standard input, 110 374 standard output and standard error file handles, respectively. Valid values 111 375 are :data:`PIPE`, an existing file descriptor (a positive integer), an 112 376 existing file object, and ``None``. :data:`PIPE` indicates that a new pipe 113 to the child should be created. With ``None``, no redirection will occur; 114 the child's file handles will be inherited from the parent. Additionally, 115 *stderr* can be :data:`STDOUT`, which indicates that the stderr data from the 116 applications should be captured into the same file handle as for stdout. 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 380 the stderr data from the child process should be captured into the same file 381 handle as for stdout. 117 382 118 383 If *preexec_fn* is set to a callable object, this object will be called in the … … 125 390 also redirect the standard handles by setting *stdin*, *stdout* or *stderr*. 126 391 127 If *shell* is :const:`True`, the specified command will be executed through the128 shell.129 130 392 If *cwd* is not ``None``, the child's current directory will be changed to *cwd* 131 393 before it is executed. Note that this directory is not considered when … … 146 408 .. _side-by-side assembly: http://en.wikipedia.org/wiki/Side-by-Side_Assembly 147 409 148 If *universal_newlines* is :const:`True`, the file objects stdout and stderr are149 opened as text files, but lines may be terminated by any of ``'\n'``, the Unix150 end-of-line convention, ``'\r'``, the old Macintosh convention or ``'\r\n'``, the151 Windows convention. All of these external representations are seen as ``'\n'``152 by the Python program.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'``, 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. 153 415 154 416 .. note:: 155 417 156 This feature is only available if Python is built with universal newline support 157 (the default). Also, the newlines attribute of the file objects :attr:`stdout`, 158 :attr:`stdin` and :attr:`stderr` are not updated by the communicate() method. 159 160 The *startupinfo* and *creationflags*, if given, will be passed to the 161 underlying CreateProcess() function. They can specify things such as appearance 162 of the main window and priority for the new process. (Windows only) 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 Convenience Functions 180 ^^^^^^^^^^^^^^^^^^^^^ 181 182 This module also defines two shortcut functions: 183 184 185 .. function:: call(*popenargs, **kwargs) 186 187 Run command with arguments. Wait for command to complete, then return the 188 :attr:`returncode` attribute. 189 190 The arguments are the same as for the Popen constructor. Example:: 191 192 retcode = call(["ls", "-l"]) 193 194 195 .. function:: check_call(*popenargs, **kwargs) 196 197 Run command with arguments. Wait for command to complete. If the exit code was 198 zero then return, otherwise raise :exc:`CalledProcessError`. The 199 :exc:`CalledProcessError` object will have the return code in the 200 :attr:`returncode` attribute. 201 202 The arguments are the same as for the Popen constructor. Example:: 203 204 check_call(["ls", "-l"]) 205 206 .. versionadded:: 2.5 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 420 :attr:`stdout`, :attr:`stdin` and :attr:`stderr` are not updated by the 421 communicate() method. 422 423 If given, *startupinfo* will be a :class:`STARTUPINFO` object, which is 424 passed to the underlying ``CreateProcess`` function. 425 *creationflags*, if given, can be :data:`CREATE_NEW_CONSOLE` or 426 :data:`CREATE_NEW_PROCESS_GROUP`. (Windows only) 207 427 208 428 … … 213 433 execute, will be re-raised in the parent. Additionally, the exception object 214 434 will have one extra attribute called :attr:`child_traceback`, which is a string 215 containing traceback information from the child s point of view.435 containing traceback information from the child's point of view. 216 436 217 437 The most common exception raised is :exc:`OSError`. This occurs, for example, … … 222 442 arguments. 223 443 224 check_call() will raise :exc:`CalledProcessError`, if the called process returns 225 a non-zero return code. 444 :func:`check_call` and :func:`check_output` will raise 445 :exc:`CalledProcessError` if the called process returns a non-zero return 446 code. 226 447 227 448 … … 229 450 ^^^^^^^^ 230 451 231 Unlike some other popen functions, this implementation will never call /bin/sh 232 implicitly. This means that all characters, including shell metacharacters, can 233 safely be passed to child processes. 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 455 shell is invoked explicitly, then it is the application's responsibility to 456 ensure that all whitespace and metacharacters are quoted appropriately. 234 457 235 458 … … 242 465 .. method:: Popen.poll() 243 466 244 Check if child process has terminated. Set and return :attr:`returncode`245 attribute.467 Check if child process has terminated. Set and return 468 :attr:`~Popen.returncode` attribute. 246 469 247 470 248 471 .. method:: Popen.wait() 249 472 250 Wait for child process to terminate. Set and return :attr:`returncode`251 attribute.473 Wait for child process to terminate. Set and return 474 :attr:`~Popen.returncode` attribute. 252 475 253 476 .. warning:: 254 477 255 This will deadlock if the child process generates enough output to a 256 stdout or stderr pipe such that it blocks waiting for the OS pipe buffer 257 to accept more data. Use :meth:`communicate` to avoid that. 478 This will deadlock when using ``stdout=PIPE`` and/or 479 ``stderr=PIPE`` and the child process generates enough output to 480 a pipe such that it blocks waiting for the OS pipe buffer to 481 accept more data. Use :meth:`communicate` to avoid that. 258 482 259 483 … … 284 508 .. note:: 285 509 286 On Windows only SIGTERM is supported so far. It's an alias for 287 :meth:`terminate`. 510 On Windows, SIGTERM is an alias for :meth:`terminate`. CTRL_C_EVENT and 511 CTRL_BREAK_EVENT can be sent to processes started with a *creationflags* 512 parameter which includes `CREATE_NEW_PROCESS_GROUP`. 288 513 289 514 .. versionadded:: 2.6 … … 293 518 294 519 Stop the child. On Posix OSs the method sends SIGTERM to the 295 child. On Windows the Win32 API function :c func:`TerminateProcess` is called520 child. On Windows the Win32 API function :c:func:`TerminateProcess` is called 296 521 to stop the child. 297 522 … … 311 536 .. warning:: 312 537 313 Use :meth:` communicate` rather than :attr:`.stdin.write <stdin>`,314 :attr:`.stdout.read < stdout>` or :attr:`.stderr.read <stderr>` to avoid538 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 315 540 deadlocks due to any of the other OS pipe buffers filling up and blocking the 316 541 child process. … … 340 565 The process ID of the child process. 341 566 567 Note that if you set the *shell* argument to ``True``, this is the process ID 568 of the spawned shell. 569 342 570 343 571 .. attribute:: Popen.returncode … … 351 579 352 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. 683 684 353 685 .. _subprocess-replacements: 354 686 355 Replacing Older Functions with the subprocessModule356 ---------------------------------------------------- 357 358 In this section, "a ==>b" means that b can be used as a replacement for a.687 Replacing Older Functions with the :mod:`subprocess` Module 688 ----------------------------------------------------------- 689 690 In this section, "a becomes b" means that b can be used as a replacement for a. 359 691 360 692 .. note:: 361 693 362 All functions in this section fail (more or less) silently if the executed 363 program cannot be found; this module raises an :exc:`OSError` exception. 364 365 In the following examples, we assume that the subprocess module is imported with 366 "from subprocess import \*". 694 All "a" functions in this section fail (more or less) silently if the 695 executed program cannot be found; the "b" replacements raise :exc:`OSError` 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 700 return code. The output is still available as the 701 :attr:`~CalledProcessError.output` attribute of the raised exception. 702 703 In the following examples, we assume that the relevant functions have already 704 been imported from the :mod:`subprocess` module. 367 705 368 706 … … 373 711 374 712 output=`mycmd myarg` 375 ==>376 output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]713 # becomes 714 output = check_output(["mycmd", "myarg"]) 377 715 378 716 … … 383 721 384 722 output=`dmesg | grep hda` 385 ==>723 # becomes 386 724 p1 = Popen(["dmesg"], stdout=PIPE) 387 725 p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) 726 p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. 388 727 output = p2.communicate()[0] 728 729 The p1.stdout.close() call after starting the p2 is important in order for p1 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) 389 738 390 739 … … 395 744 396 745 sts = os.system("mycmd" + " myarg") 397 ==> 398 p = Popen("mycmd" + " myarg", shell=True) 399 sts = os.waitpid(p.pid, 0)[1] 746 # becomes 747 sts = call("mycmd" + " myarg", shell=True) 400 748 401 749 Notes: 402 750 403 751 * Calling the program through the shell is usually not required. 404 405 * It's easier to look at the :attr:`returncode` attribute than the exit status.406 752 407 753 A more realistic example would look like this:: … … 413 759 else: 414 760 print >>sys.stderr, "Child returned", retcode 415 except OSError ,e:761 except OSError as e: 416 762 print >>sys.stderr, "Execution failed:", e 417 763 … … 505 851 ... 506 852 rc = pipe.close() 507 if rc != None and rc % 256:853 if rc is not None and rc >> 8: 508 854 print "There were some errors" 509 855 ==> … … 549 895 ``close_fds=True`` with :class:`Popen`. 550 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
Note:
See TracChangeset
for help on using the changeset viewer.