subprocess --- 子行程管理¶
The subprocess module allows you to spawn new processes, connect to their
input/output/error pipes, and obtain their return codes. This module intends to
replace several older modules and functions:
os.system
os.spawn*
Information about how the subprocess module can be used to replace these
modules and functions can be found in the following sections.
也參考
PEP 324 -- 提議 subprocess 模組的 PEP
可用性: not Android, not iOS, not WASI.
此模組在行動平台或 WebAssembly 平台上不支援。
使用 subprocess 模組¶
The recommended approach to invoking subprocesses is to use the run()
function for all use cases it can handle. For more advanced use cases, the
underlying Popen interface can be used directly.
- subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None, **other_popen_kwargs)¶
Run the command described by args. Wait for command to complete, then return a
CompletedProcessinstance.The arguments shown above are merely the most common ones, described below in Frequently Used Arguments (hence the use of keyword-only notation in the abbreviated signature). The full function signature is largely the same as that of the
Popenconstructor - most of the arguments to this function are passed through to that interface. (timeout, input, check, and capture_output are not.)If capture_output is true, stdout and stderr will be captured. When used, the internal
Popenobject is automatically created with stdout and stderr both set toPIPE. The stdout and stderr arguments may not be supplied at the same time as capture_output. If you wish to capture and combine both streams into one, set stdout toPIPEand stderr toSTDOUT, instead of using capture_output.A timeout may be specified in seconds, it is internally passed on to
Popen.communicate(). If the timeout expires, the child process will be killed and waited for. TheTimeoutExpiredexception will be re-raised after the child process has terminated. The initial process creation itself cannot be interrupted on many platform APIs so you are not guaranteed to see a timeout exception until at least after however long process creation takes.The input argument is passed to
Popen.communicate()and thus to the subprocess's stdin. If used it must be a byte sequence, or a string if encoding or errors is specified or text is true. When used, the internalPopenobject is automatically created with stdin set toPIPE, and the stdin argument may not be used as well.If check is true, and the process exits with a non-zero exit code, a
CalledProcessErrorexception will be raised. Attributes of that exception hold the arguments, the exit code, and stdout and stderr if they were captured.If encoding or errors are specified, or text is true, file objects for stdin, stdout and stderr are opened in text mode using the specified encoding and errors or the
io.TextIOWrapperdefault. The universal_newlines argument is equivalent to text and is provided for backwards compatibility. By default, file objects are opened in binary mode.If env is not
None, it must be a mapping that defines the environment variables for the new process; these are used instead of the default behavior of inheriting the current process' environment. It is passed directly toPopen. This mapping can be str to str on any platform or bytes to bytes on POSIX platforms much likeos.environoros.environb.範例:
>>> subprocess.run(["ls", "-l"]) # 不捕捉輸出 CompletedProcess(args=['ls', '-l'], returncode=0) >>> subprocess.run("exit 1", shell=True, check=True) Traceback (most recent call last): ... subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1 >>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True) CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0, stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
在 3.5 版被加入.
在 3.6 版的變更: 新增 encoding 與 errors 參數。
在 3.7 版的變更: Added the text parameter, as a more understandable alias of universal_newlines. Added the capture_output parameter.
在 3.12 版的變更: Changed Windows shell search order for
shell=True. The current directory and%PATH%are replaced with%COMSPEC%and%SystemRoot%\System32\cmd.exe. As a result, dropping a malicious program namedcmd.exeinto a current directory no longer works.
- class subprocess.CompletedProcess¶
The return value from
run(), representing a process that has finished.- args¶
The arguments used to launch the process. This may be a list or a string.
- returncode¶
Exit status of the child process. Typically, an exit status of 0 indicates that it ran successfully.
A negative value
-Nindicates that the child was terminated by signalN(POSIX only).
- stdout¶
Captured stdout from the child process. A bytes sequence, or a string if
run()was called with an encoding, errors, or text=True.Noneif stdout was not captured.If you ran the process with
stderr=subprocess.STDOUT, stdout and stderr will be combined in this attribute, andstderrwill beNone.
- stderr¶
Captured stderr from the child process. A bytes sequence, or a string if
run()was called with an encoding, errors, or text=True.Noneif stderr was not captured.
- check_returncode()¶
If
returncodeis non-zero, raise aCalledProcessError.
在 3.5 版被加入.
- subprocess.DEVNULL¶
Special value that can be used as the stdin, stdout or stderr argument to
Popenand indicates that the special fileos.devnullwill be used.在 3.3 版被加入.
- subprocess.PIPE¶
Special value that can be used as the stdin, stdout or stderr argument to
Popenand indicates that a pipe to the standard stream should be opened. Most useful withPopen.communicate().
- subprocess.STDOUT¶
Special value that can be used as the stderr argument to
Popenand indicates that standard error should go into the same handle as standard output.
- exception subprocess.SubprocessError¶
Base class for all other exceptions from this module.
在 3.3 版被加入.
- exception subprocess.TimeoutExpired¶
Subclass of
SubprocessError, raised when a timeout expires while waiting for a child process.- cmd¶
Command that was used to spawn the child process.
- timeout¶
Timeout in seconds.
- output¶
Output of the child process if it was captured by
run()orcheck_output(). Otherwise,None. This is alwaysbyteswhen any output was captured regardless of thetext=Truesetting. It may remainNoneinstead ofb''when no output was observed.
- stderr¶
Stderr output of the child process if it was captured by
run(). Otherwise,None. This is alwaysbyteswhen stderr output was captured regardless of thetext=Truesetting. It may remainNoneinstead ofb''when no stderr output was observed.
在 3.3 版被加入.
在 3.5 版的變更: stdout and stderr attributes added
- exception subprocess.CalledProcessError¶
Subclass of
SubprocessError, raised when a process run bycheck_call(),check_output(), orrun()(withcheck=True) returns a non-zero exit status.- returncode¶
Exit status of the child process. If the process exited due to a signal, this will be the negative signal number.
- cmd¶
Command that was used to spawn the child process.
- output¶
Output of the child process if it was captured by
run()orcheck_output(). Otherwise,None.
在 3.5 版的變更: stdout and stderr attributes added
Frequently Used Arguments¶
To support a wide variety of use cases, the Popen constructor (and
the convenience functions) accept a large number of optional arguments. For
most typical use cases, many of these arguments can be safely left at their
default values. The arguments that are most commonly needed are:
args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be
True(see below) or else the string must simply name the program to be executed without specifying any arguments.stdin, stdout and stderr specify the executed program's standard input, standard output and standard error file handles, respectively. Valid values are
None,PIPE,DEVNULL, an existing file descriptor (a positive integer), and an existing file object with a valid file descriptor. With the default settings ofNone, no redirection will occur.PIPEindicates that a new pipe to the child should be created.DEVNULLindicates that the special file