subprocessSubprocess management子流程管理

Source code: Lib/subprocess.py


The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. subprocess模块允许您生成新流程,连接到它们的输入/输出/错误管道,并获取它们的返回代码。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.有关如何使用subprocess模块替换这些模块和函数的信息,请参阅以下部分。

See also

PEP 324PEP proposing the subprocess modulePEP提出子流程模块

Using the 使用subprocess Module模块

The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle. 调用子流程的推荐方法是对所有可以处理的用例使用run()函数。For more advanced use cases, the underlying Popen interface can be used directly.对于更高级的用例,可以直接使用底层Popen接口。

The run() function was added in Python 3.5; if you need to retain compatibility with older versions, see the Older high-level API section.在Python 3.5中添加了run()函数;如果需要保持与旧版本的兼容性,请参阅Older high-level API部分。

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. 运行args描述的命令。Wait for command to complete, then return a CompletedProcess instance.等待命令完成,然后返回一个CompletedProcess实例。

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 Popen constructor - most of the arguments to this function are passed through to that interface. 完整的函数签名与Popen构造函数的签名基本相同——该函数的大多数参数都传递给该接口。(timeout, input, check, and capture_output are not.)timeoutinputcheckcapture_output都不是。)

If capture_output is true, stdout and stderr will be captured. 如果capture_outputtrue,则将捕获stdoutstderrWhen used, the internal Popen object is automatically created with stdout=PIPE and stderr=PIPE. 使用时,内部Popen对象将自动创建为stdout=PIPEstderr=PIPEThe stdout and stderr arguments may not be supplied at the same time as capture_output. stdoutstderr参数不能与capture_output同时提供。If you wish to capture and combine both streams into one, use stdout=PIPE and stderr=STDOUT instead of capture_output.如果希望捕获两个流并将其合并为一个流,请使用stdout=PIPEstderr=STDOUT,而不是capture_output

The timeout argument is passed to Popen.communicate(). timeout参数传递给Popen.communicate()If the timeout expires, the child process will be killed and waited for. 如果超时过期,子进程将被终止并等待。The TimeoutExpired exception will be re-raised after the child process has terminated.子进程终止后,将重新引发TimeoutExpired异常。

The input argument is passed to Popen.communicate() and thus to the subprocess’s stdin. input参数传递给Popen.communicate(),从而传递给子进程的stdin。If used it must be a byte sequence, or a string if encoding or errors is specified or text is true. 如果使用,则必须是字节序列,如果指定了encodingerrorstext为真,则必须为字符串。When used, the internal Popen object is automatically created with stdin=PIPE, and the stdin argument may not be used as well.使用时,内部Popen对象会自动创建为stdin=PIPE,而stdin参数也可能不使用。

If check is true, and the process exits with a non-zero exit code, a CalledProcessError exception will be raised. 如果checktrue,并且进程以非零退出代码退出,则将引发CalledProcessError异常。Attributes of that exception hold the arguments, the exit code, and stdout and stderr if they were captured.该异常的属性包含参数、退出代码以及stdout和stderr(如果已捕获)。

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.TextIOWrapper default. 如果指定了encodingerrors,或者texttrue,则使用指定的encodingerrorsio.TextIOWrapper默认值以文本模式打开stdin、stdout和stderr的文件对象。The universal_newlines argument is equivalent to text and is provided for backwards compatibility. universal_newlines参数等效于text,并提供向后兼容性。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. 如果env不是None,那么它必须是定义新流程的环境变量的映射;它们被用来代替继承当前进程环境的默认行为。It is passed directly to Popen.它直接传递给Popen

Examples:

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
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'')

New in version 3.5.版本3.5中新增。

Changed in version 3.6:版本3.6中更改: Added encoding and errors parameters添加了encodingerrors参数

Changed in version 3.7:版本3.7中更改: Added the text parameter, as a more understandable alias of universal_newlines. 添加了text参数,作为universal_newlines的更易于理解的别名。Added the capture_output parameter.添加了capture_output参数。

classsubprocess.CompletedProcess

The return value from run(), representing a process that has finished.run()的返回值,表示已完成的进程。

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.子进程的退出状态。通常,退出状态为0表示已成功运行。

A negative value -N indicates that the child was terminated by signal N (POSIX only).负值-N表示子进程由信号N终止(仅限POSIX)。

stdout

Captured stdout from the child process. 从子进程捕获标准输出。A bytes sequence, or a string if run() was called with an encoding, errors, or text=True. 一个字节序列,或者一个字符串,如果使用编码、错误或text=True调用run()None if stdout was not captured.如果未捕获stdout,则None

If you ran the process with stderr=subprocess.STDOUT, stdout and stderr will be combined in this attribute, and stderr will be None.如果使用stderr=subprocess.STDOUT运行进程,则stdout和stderr将在此属性中组合,并且stderrNone

stderr

Captured stderr from the child process. 已从子进程捕获stderr。A bytes sequence, or a string if run() was called with an encoding, errors, or text=True. 一个字节序列,或者一个字符串,如果使用编码、错误或text=True调用run()None if stderr was not captured.如果未捕获stderr,则为None

check_returncode()

If returncode is non-zero, raise a CalledProcessError.如果returncode为非零,则引发CalledProcessError

New in version 3.5.版本3.5中新增。

subprocess.DEVNULL

Special value that can be used as the stdin, stdout or stderr argument to Popen and indicates that the special file os.devnull will be used.可以用作Popenstdinstdoutstderr参数的特殊值,表示将使用特殊文件os.devnull

New in version 3.3.版本3.3中新增。

subprocess.PIPE

Special value that can be used as the stdin, stdout or stderr argument to Popen and indicates that a pipe to the standard stream should be opened. 可以用作Popenstdinstdoutstderr参数的特殊值,指示应该打开到标准流的管道。Most useful with Popen.communicate().Popen.communicate()最有用。

subprocess.STDOUT

Special value that can be used as the stderr argument to Popen and indicates that standard error should go into the same handle as standard output.可以用作Popenstderr参数的特殊值,指示标准错误应该与标准输出进入相同的句柄。

exceptionsubprocess.SubprocessError

Base class for all other exceptions from this module.此模块中所有其他异常的基类。

New in version 3.3.版本3.3中新增。

exceptionsubprocess.TimeoutExpired

Subclass of SubprocessError, raised when a timeout expires while waiting for a child process.SubprocessError的子类,在等待子进程时超时时引发。

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() or check_output(). 子进程的输出(如果它被run()check_output()捕获)。Otherwise, None.否则,为None

stdout

Alias for output, for symmetry with stderr.用于输出的别名,用于与stderr对称。

stderr

Stderr output of the child process if it was captured by run(). 子进程的Stderr输出(如果它被run()捕获)。Otherwise, None.否则,None

New in version 3.3.版本3.3中新增。

Changed in version 3.5:版本3.5中更改: stdout and stderr attributes added添加了stdoutstderr属性

exceptionsubprocess.CalledProcessError

Subclass of SubprocessError, raised when a process run by check_call() or check_output() returns a non-zero exit status.SubprocessError的子类,当check_call()check_output()运行的进程返回非零退出状态时引发。

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() or check_output(). 子进程的输出(如果它被run()check_output()捕获)。Otherwise, None.否则,为None

stdout

Alias for output, for symmetry with stderr.输出的别名,用于与stderr对称。

stderr

Stderr output of the child process if it was captured by run(). 子进程的Stderr输出(如果它被run()捕获)。Otherwise, None.否则,为None

Changed in version 3.5:版本3.5中更改: stdout and stderr attributes added添加了stdoutstderr属性

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. 为了支持各种各样的用例,Popen构造函数(和方便函数)接受大量可选参数。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. 所有调用都需要args,它应该是字符串或程序参数序列。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.如果传递单个字符串,则shell必须为True(见下文),否则字符串必须简单地命名要执行的程序,而不指定任何参数。

stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. stdinstdoutstderr分别指定执行程序的标准输入、标准输出和标准错误文件句柄。Valid values are PIPE, DEVNULL, an existing file descriptor (a positive integer), an existing file object with a valid file descriptor, and None. 有效值为PIPEDEVNULL、现有文件描述符(正整数)、具有有效文件描述符的现有文件对象和NonePIPE indicates that a new pipe to the child should be created. PIPE指示应创建子级的新管道。DEVNULL indicates that the special file os.devnull will be used. DEVNULL表示将使用特殊文件os.devnullWith the default settings of None, no redirection will occur; the child’s file handles will be inherited from the parent. 默认设置为None时,不会发生重定向;子级的文件句柄将从父级继承。Additionally, stderr can be STDOUT, which indicates that the stderr data from the child process should be captured into the same file handle as for stdout.此外,stderr可以是STDOUT,这表示子进程的stderr数据应该捕获到与STDOUT相同的文件句柄中。

If encoding or errors are specified, or text (also known as universal_newlines) is true, the file objects stdin, stdout and stderr will be opened in text mode using the encoding and errors specified in the call or the defaults for io.TextIOWrapper.如果指定了encodingerrors,或者text(也称为universal_newlines)为true,则将使用调用中指定的编码和错误或io.TextIOWrapper的默认值以文本模式打开文件对象stdinstdoutstderr

For stdin, line ending characters '\n' in the input will be converted to the default line separator os.linesep. 对于stdin,输入中的行结束字符'\n'将转换为默认的行分隔符os.linesepFor stdout and stderr, all line endings in the output will be converted to '\n'. 对于stdoutstderr,输出中的所有行结尾都将转换为'\n'For more information see the documentation of the io.TextIOWrapper class when the newline argument to its constructor is None.有关更多信息,请参阅io.TextIOWrapper类的文档,当其构造函数的newline参数为None时。

If text mode is not used, stdin, stdout and stderr will be opened as binary streams. 如果不使用文本模式,则stdinstdoutstderr将作为二进制流打开。No encoding or line ending conversion is performed.不执行编码或行尾转换。

New in version 3.6.版本3.6中新增。Added encoding and errors parameters.添加了encodingerrors参数。

New in version 3.7.版本3.7中新增。Added the text parameter as an alias for universal_newlines.添加了text参数作为universal_newlines的别名。

Note

The newlines attribute of the file objects Popen.stdin, Popen.stdout and Popen.stderr are not updated by the Popen.communicate() method.Popen.communicate()方法不会更新文件对象Popen.stdinPopen.stdoutPopen.stderr的换行符属性。

If shell is True, the specified command will be executed through the shell. 如果shellTrue,则指定的命令将通过shell执行。This can be useful if you are using Python primarily for the enhanced control flow it offers over most system shells and still want convenient access to other shell features such as shell pipes, filename wildcards, environment variable expansion, and expansion of ~ to a user’s home directory. 如果您使用Python主要是为了增强对大多数系统shell的控制流,并且仍然希望方便地访问其他shell功能,例如shell管道、文件名通配符、环境变量扩展和用户主目录的~扩展,那么这将非常有用。However, note that Python itself offers implementations of many shell-like features (in particular, glob, fnmatch, os.walk(), os.path.expandvars(), os.path.expanduser(), and shutil).然而,请注意,Python本身提供了许多类似于shell的功能(特别是globfnmatchos.walk()os.path.expandvars()os.path.expanduser()shutil)的实现。

Changed in version 3.3:版本3.3中更改: When universal_newlines is True, the class uses the encoding locale.getpreferredencoding(False) instead of locale.getpreferredencoding(). universal_newlinesTrue时,该类使用编码locale.getpreferredencoding(False)而不是locale.getpreferredencoding()See the io.TextIOWrapper class for more information on this change.有关此更改的详细信息,请参阅io.TextIOWrapper类。

Note

Read the Security Considerations section before using shell=True.在使用shell=True之前,请阅读安全注意事项部分。

These options, along with all of the other options, are described in more detail in the Popen constructor documentation.这些选项以及所有其他选项在Popen构造函数文档中有更详细的描述。

Popen ConstructorPopen构造函数

The underlying process creation and management in this module is handled by the Popen class. 本模块中的底层流程创建和管理由Popen类处理。It offers a lot of flexibility so that developers are able to handle the less common cases not covered by the convenience functions.它提供了很大的灵活性,因此开发人员能够处理方便功能未涵盖的不太常见的情况。

classsubprocess.Popen(args, bufsize=- 1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=None, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, group=None, extra_groups=None, user=None, umask=- 1, encoding=None, errors=None, text=None, pipesize=- 1)

Execute a child program in a new process. 在新进程中执行子程序。On POSIX, the class uses os.execvpe()-like behavior to execute the child program. 在POSIX上,类使用os.execvpe()类行为来执行子程序。On Windows, the class uses the Windows CreateProcess() function. 在Windows上,该类使用Windows CreateProcess()函数。The arguments to Popen are as follows.Popen的参数如下。

args should be a sequence of program arguments or else a single string or path-like object. args应该是一系列程序参数,或者是一个字符串或类路径对象By default, the program to execute is the first item in args if args is a sequence. 默认情况下,如果args是序列,则要执行的程序是args中的第一项。If args is a string, the interpretation is platform-dependent and described below. 如果args是字符串,则解释取决于平台,如下所述。See the shell and executable arguments for additional differences from the default behavior. 有关与默认行为的其他差异,请参阅shellexecutable参数。Unless otherwise stated, it is recommended to pass args as a sequence.除非另有说明,否则建议将args作为序列传递。

Warning

For maximum reliability, use a fully-qualified path for the executable. 为了获得最大的可靠性,请为可执行文件使用完全限定的路径。To search for an unqualified name on PATH, use shutil.which(). 要在PATH上搜索非限定名称,请使用shutil.which()On all platforms, passing sys.executable is the recommended way to launch the current Python interpreter again, and use the -m command-line format to launch an installed module.在所有平台上,传递sys.executable是再次启动当前Python解释器并使用-m命令行格式启动已安装模块的推荐方法。

Resolving the path of executable (or the first item of args) is platform dependent. 解析executable(或第一项args)的路径取决于平台。For POSIX, see os.execvpe(), and note that when resolving or searching for the executable path, cwd overrides the current working directory and env can override the PATH environment variable. 对于POSIX,请参阅os.execvpe(),并注意在解析或搜索可执行路径时,cwd会覆盖当前工作目录,env会覆盖path环境变量。For Windows, see the documentation of the lpApplicationName and lpCommandLine parameters of WinAPI CreateProcess, and note that when resolving or searching for the executable path with shell=False, cwd does not override the current working directory and env cannot override the PATH environment variable. 对于Windows,请参阅WinAPI CreateProcess的lpApplicationNamelpCommandLine参数的文档,并注意在使用shell=False解析或搜索可执行路径时,cwd不会覆盖当前工作目录,env也无法覆盖PATH环境变量。Using a full path avoids all of these variations.使用完整路径可以避免所有这些变化。

An example of passing some arguments to an external program as a sequence is:将一些参数作为序列传递给外部程序的示例如下:

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])

On POSIX, if args is a string, the string is interpreted as the name or path of the program to execute. 在POSIX上,如果args是字符串,则该字符串被解释为要执行的程序的名称或路径。However, this can only be done if not passing arguments to the program.然而,这只能在不向程序传递参数的情况下进行。

Note

It may not be obvious how to break a shell command into a sequence of arguments, especially in complex cases. 如何将shell命令分解为一系列参数可能并不明显,尤其是在复杂的情况下。shlex.split() can illustrate how to determine the correct tokenization for args:shlex.split()可以说明如何确定args的正确标记化:

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!

Note in particular that options (such as -input) and arguments (such as eggs.txt) that are separated by whitespace in the shell go in separate list elements, while arguments that need quoting or backslash escaping when used in the shell (such as filenames containing spaces or the echo command shown above) are single list elements.特别注意,shell中用空格分隔的选项(如-input)和参数(如eggs.txt)位于单独的列表元素中,而在shell中使用时需要引号或反斜杠转义的参数(如包含空格的文件名或上面显示的echo命令)是单个列表元素。

On Windows, if args is a sequence, it will be converted to a string in a manner described in Converting an argument sequence to a string on Windows. 在Windows上,如果args是一个序列,它将按照Windows上将参数序列转换为字符串中所述的方式转换为字符串This is because the underlying CreateProcess() operates on strings.这是因为基础CreateProcess()对字符串进行操作。

Changed in version 3.6:版本3.6中更改: args parameter accepts a path-like object if shell is False and a sequence containing path-like objects on POSIX.如果shellFalseargs参数接受类路径对象,并且接受POSIX上包含路径类对象的序列。

Changed in version 3.8:版本3.8中更改: args parameter accepts a path-like object if shell is False and a sequence containing bytes and path-like objects on Windows.如果shellFalseargs参数接受类路径对象,并且在Windows上接受包含字节和路径类对象的序列。

The shell argument (which defaults to False) specifies whether to use the shell as the program to execute. shell参数(默认为False)指定是否使用shell作为要执行的程序。If shell is True, it is recommended to pass args as a string rather than as a sequence.如果shell为True,建议将args作为字符串而不是序列传递。

On POSIX with shell=True, the shell defaults to /bin/sh. shell=True的POSIX上,shell默认为/bin/shIf args is a string, the string specifies the command to execute through the shell. 如果args是字符串,则该字符串指定要通过shell执行的命令。This means that the string must be formatted exactly as it would be when typed at the shell prompt. 这意味着字符串的格式必须与在shell提示符下键入时的格式完全相同。This includes, for example, quoting or backslash escaping filenames with spaces in them. 例如,这包括引号或反斜杠转义文件名,其中包含空格。If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself. 如果args是一个序列,则第一项指定命令字符串,任何其他项都将被视为shell本身的附加参数。That is to say, Popen does the equivalent of:也就是说,Popen做的相当于:

Popen(['/bin/sh', '-c', args[0], args[1], ...])

On Windows with shell=True, the COMSPEC environment variable specifies the default shell. shell=True的Windows上,COMSPEC环境变量指定默认shell。The only time you need to specify shell=True on Windows is when the command you wish to execute is built into the shell (e.g. dir or copy). 在Windows上,唯一需要指定shell=True的时间是您希望执行的命令内置在shell中时(例如dircopy)。You do not need shell=True to run a batch file or console-based executable.运行批处理文件或基于控制台的可执行文件不需要shell=True

Note

Read the Security Considerations section before using shell=True.在使用shell=True之前,请阅读安全注意事项部分。

bufsize will be supplied as the corresponding argument to the open() function when creating the stdin/stdout/stderr pipe file objects:创建stdin/stdout/stderr管道文件对象时,bufsize将作为open()函数的对应参数提供:

  • 0 means unbuffered (read and write are one system call and can return short)0表示无缓冲区(读和写是一个系统调用,可以短返回)

  • 1 means line buffered (only usable if universal_newlines=True i.e., in a text mode)1表示缓存行(仅当universal_newlines=True时可用,即在文本模式下)

  • any other positive value means use a buffer of approximately that size任何其他正值表示使用近似于该大小的缓冲区

  • negative bufsize (the default) means the system default of io.DEFAULT_BUFFER_SIZE will be used.负bufsize(默认值)表示将使用io.DEFAULT_BUFFER_SIZE的系统默认值。

Changed in version 3.3.1:版本3.3.1中更改: bufsize now defaults to -1 to enable buffering by default to match the behavior that most code expects. bufsize现在默认为-1,以默认启用缓冲以匹配大多数代码所期望的行为。In versions prior to Python 3.2.4 and 3.3.1 it incorrectly defaulted to 0 which was unbuffered and allowed short reads. 在Python 3.2.4和3.3.1之前的版本中,它错误地默认为0,这是无缓冲的,允许短读。This was unintentional and did not match the behavior of Python 2 as most code expected.这是无意的,与大多数代码预期的Python 2的行为不匹配。

The executable argument specifies a replacement program to execute. executable参数指定要执行的替换程序。It is very seldom needed. 很少需要它。When shell=False, executable replaces the program to execute specified by args. shell=False时,executable替换由参数指定的要执行的程序。However, the original args is still passed to the program. 但是,原始args仍然传递给程序。Most programs treat the program specified by args as the command name, which can then be different from the program actually executed. 大多数程序将args指定的程序视为命令名,这可能与实际执行的程序不同。On POSIX, the args name becomes the display name for the executable in utilities such as ps. 在POSIX上,args名称成为ps等实用程序中可执行文件的显示名称。If shell=True, on POSIX the executable argument specifies a replacement shell for the default /bin/sh.如果shell=True,则在POSIX上,executable参数指定默认/bin/sh的替换shell。

Changed in version 3.6:版本3.6中更改: executable parameter accepts a path-like object on POSIX.executable参数接受POSIX上的类路径对象

Changed in version 3.8:版本3.8中更改: executable parameter accepts a bytes and path-like object on Windows.executable参数在Windows上接受字节和类路径对象

stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. stdinstdoutstderr分别指定执行程序的标准输入、标准输出和标准错误文件句柄。Valid values are PIPE, DEVNULL, an existing file descriptor (a positive integer), an existing file object with a valid file descriptor, and None. 有效值为PIPEDEVNULL、现有文件描述符(正整数)、具有有效文件描述符的现有文件对象NonePIPE indicates that a new pipe to the child should be created. PIPE指示应创建子级的新管道。DEVNULL indicates that the special file os.devnull will be used. With the default settings of None, no redirection will occur; the child’s file handles will be inherited from the parent. 默认设置为None时,不会发生重定向;子级的文件句柄将从父级继承。Additionally, stderr can be STDOUT, which indicates that the stderr data from the applications should be captured into the same file handle as for stdout.此外,stderr可以是STDOUT,这表示应用程序中的stderr数据应该捕获到与STDOUT相同的文件句柄中。

If preexec_fn is set to a callable object, this object will be called in the child process just before the child is executed. (POSIX only)如果predec_fn设置为可调用对象,则在执行子进程之前,将在子进程中调用该对象。(仅限POSIX)

Warning

The preexec_fn parameter is not safe to use in the presence of threads in your application. predec_fn参数在应用程序中存在线程时使用不安全。The child process could deadlock before exec is called. 子进程在调用exec之前可能会死锁。If you must use it, keep it trivial! Minimize the number of libraries you call into.如果您必须使用它,请保持它微不足道!尽量减少调用的库的数量。

Note

If you need to modify the environment for the child use the env parameter rather than doing it in a preexec_fn. 如果需要修改子对象的环境,请使用env参数,而不是在predec_fn中执行。The start_new_session parameter can take the place of a previously common use of preexec_fn to call os.setsid() in the child.start_new_session参数可以代替先前常用的predec_fn来调用子级中的os.setsid()

Changed in version 3.8:版本3.8中更改: The preexec_fn parameter is no longer supported in subinterpreters. 子企业不再支持predec_fn参数。The use of the parameter in a subinterpreter raises RuntimeError. 在子企业中使用参数会引发RuntimeErrorThe new restriction may affect applications that are deployed in mod_wsgi, uWSGI, and other embedded environments.新的限制可能会影响部署在mod_wsgi、uWSGI和其他嵌入式环境中的应用程序。

If close_fds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed. 如果close_fdstrue,则在执行子进程之前,将关闭除012之外的所有文件描述符。Otherwise when close_fds is false, file descriptors obey their inheritable flag as described in Inheritance of File Descriptors.否则,当close_fdsfalse时,文件描述符将遵循其可继承标志,如文件描述符继承中所述。

On Windows, if close_fds is true then no handles will be inherited by the child process unless explicitly passed in the handle_list element of STARTUPINFO.lpAttributeList, or by standard handle redirection.在Windows上,如果close_fdstrue,则子进程将不会继承句柄,除非在STARTUPINFO.lpAttributeListhandle_list元素中显式传递,或通过标准句柄重定向传递。

Changed in version 3.2:版本3.2中更改: The default for close_fds was changed from False to what is described above.close_fds的默认值从False更改为上述值。

Changed in version 3.7:版本3.7中更改: On Windows the default for close_fds was changed from False to True when redirecting the standard handles. 在Windows上,重定向标准句柄时,close_fds的默认值从False更改为TrueIt’s now possible to set close_fds to True when redirecting the standard handles.现在可以在重定向标准句柄时将close_fds设置为True

pass_fds is an optional sequence of file descriptors to keep open between the parent and child. pass_fds是一个可选的文件描述符序列,用于在父级和子级之间保持打开状态。Providing any pass_fds forces close_fds to be True. 提供任何pass_fds都会强制close_fdsTrue(POSIX only)

Changed in version 3.2:版本3.2中更改: The pass_fds parameter was added.已添加pass_fds参数。

If cwd is not None, the function changes the working directory to cwd before executing the child. 如果cwd不是None,则函数在执行子级之前将工作目录更改为cwdcwd can be a string, bytes or path-like object. cwd可以是字符串、字节或类路径对象On POSIX, the function looks for executable (or for the first item in args) relative to cwd if the executable path is a relative path.在POSIX上,如果可执行路径是相对路径,则函数查找与cwd相关的executable(或参数中的第一项)。

Changed in version 3.6:版本3.6中更改: cwd parameter accepts a path-like object on POSIX.cwd参数接受POSIX上类路径对象

Changed in version 3.7:版本3.7中更改: cwd parameter accepts a path-like object on Windows.cwd参数在Windows上接受类路径对象

Changed in version 3.8:版本3.8中更改: cwd parameter accepts a bytes object on Windows.cwd参数接受Windows上的字节对象。

If restore_signals is true (the default) all signals that Python has set to SIG_IGN are restored to SIG_DFL in the child process before the exec. 如果restore_signalstrue(默认值),Python设置为SIG_IGN的所有信号都将在执行之前在子进程中恢复为SIG_DFL。Currently this includes the SIGPIPE, SIGXFZ and SIGXFSZ signals. 目前,这包括SIGPIPE、SIGXFZ和SIGXFSZ信号。(POSIX only)

Changed in version 3.2:版本3.2中更改: restore_signals was added.已添加restore_signals

If start_new_session is true the setsid() system call will be made in the child process prior to the execution of the subprocess. 如果start_new_sessiontrue,则在执行子流程之前,将在子流程中进行setsid()系统调用。(POSIX only)

Changed in version 3.2:版本3.2中更改: start_new_session was added.

If group is not None, the setregid() system call will be made in the child process prior to the execution of the subprocess. 如果group不是None,则在执行子流程之前,将在子流程中进行setregid()系统调用。If the provided value is a string, it will be looked up via grp.getgrnam() and the value in gr_gid will be used. 如果提供的值是字符串,则将通过grp.getgrnam()查找该值,并使用gr_gid中的值。If the value is an integer, it will be passed verbatim. 如果该值是整数,则将逐字传递。(POSIX only)

Availability: POSIX

New in version 3.9.版本3.9中新增。

If extra_groups is not None, the setgroups() system call will be made in the child process prior to the execution of the subprocess. 如果extra_groups不是None,则在执行子流程之前,将在子流程中进行setgroups()系统调用。Strings provided in extra_groups will be looked up via grp.getgrnam() and the values in gr_gid will be used. extra_groups中提供的字符串将通过grp.getgrnam()查找,并使用gr_gid中的值。Integer values will be passed verbatim. (POSIX only)整数值将逐字传递。(仅限POSIX)

Availability: POSIX

New in version 3.9.版本3.9中新增。

If user is not None, the setreuid() system call will be made in the child process prior to the execution of the subprocess. 如果user不是None,则在执行子流程之前,将在子流程中进行setreuid()系统调用。If the provided value is a string, it will be looked up via pwd.getpwnam() and the value in pw_uid will be used. 如果提供的值是字符串,则将通过pwd.getpwnam()查找该值,并使用pw_uid中的值。If the value is an integer, it will be passed verbatim. 如果该值是整数,则将逐字传递。(POSIX only)

Availability: POSIX

New in version 3.9.版本3.9中新增。

If umask is not negative, the umask() system call will be made in the child process prior to the execution of the subprocess.如果umask不是负的,那么将在子进程执行之前在子进程中进行umask()系统调用。

Availability: POSIX

New in version 3.9.版本3.9中新增。

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.如果env不是None,那么它必须是定义新流程的环境变量的映射;它们被用来代替继承当前进程环境的默认行为。

Note

If specified, env must provide any variables required for the program to execute. 如果指定,env必须提供程序执行所需的任何变量。On Windows, in order to run a side-by-side assembly the specified env must include a valid SystemRoot.在Windows上,为了运行并行程序集,指定的env必须包含有效的SystemRoot

If encoding or errors are specified, or text is true, the file objects stdin, stdout and stderr are opened in text mode with the specified encoding and errors, as described above in Frequently Used Arguments. 如果指定了encodingerrors,或者texttrue,则文件对象stdinstdoutstderr将以文本模式打开,并带有指定的编码和errors,如上文常用参数中所述。The universal_newlines argument is equivalent to text and is provided for backwards compatibility. universal_newlines参数等效于text,并提供向后兼容性。By default, file objects are opened in binary mode.默认情况下,文件对象以二进制模式打开。

New in version 3.6.版本3.6中新增。encoding and errors were added.添加了encodingerrors

New in version 3.7.版本3.7中新增。text was added as a more readable alias for universal_newlines.text被添加为universal_newlines的更可读别名。

If given, startupinfo will be a STARTUPINFO object, which is passed to the underlying CreateProcess function. 如果给定,startupinfo将是STARTUPINFO对象,该对象将传递给基础CreateProcess函数。creationflags, if given, can be one or more of the following flags:如果给定了creationflagscreationflags可以是以下一个或多个标志:

pipesize can be used to change the size of the pipe when PIPE is used for stdin, stdout or stderr. PIPE用于stdinstdoutstderr时,pipesize可用于更改管道的大小。The size of the pipe is only changed on platforms that support this (only Linux at this time of writing). Other platforms will ignore this parameter.管道的大小仅在支持此功能的平台上更改(在撰写本文时仅限于Linux)。其他平台将忽略此参数。

New in version 3.10.版本3.10中新增。The pipesize parameter was added.

Popen objects are supported as context managers via the with statement: on exit, standard file descriptors are closed, and the process is waited for.Popen对象通过with语句被支持作为上下文管理器:退出时,关闭标准文件描述符,等待进程。

with Popen(["ifconfig"], stdout=PIPE) as proc:
log.write(proc.stdout.read())

Popen and the other functions in this module that use it raise an auditing event subprocess.Popen with arguments executable, args, cwd, and env. Popen和此模块中使用它的其他函数使用参数executableargscwdenv引发审核事件subprocess.PopenThe value for args may be a single string or a list of strings, depending on platform.args的值可以是单个字符串或字符串列表,具体取决于平台。

Changed in version 3.2:版本3.2中更改: Added context manager support.添加了上下文管理器支持。

Changed in version 3.6:版本3.6中更改: Popen destructor now emits a ResourceWarning warning if the child process is still running.如果子进程仍在运行,Popen析构函数现在会发出ResourceWarning警告。

Changed in version 3.8:版本3.8中更改: Popen can use os.posix_spawn() in some cases for better performance. Popen在某些情况下可以使用os.posix_spawn()以获得更好的性能。On Windows Subsystem for Linux and QEMU User Emulation, Popen constructor using os.posix_spawn() no longer raise an exception on errors like missing program, but the child process fails with a non-zero returncode.在Windows Subsystem for Linux和QEMU User Emulation上,使用os.posix_spawn()的Popen构造函数不再在缺少程序等错误上引发异常,但子进程失败,returncode为非零。

Exceptions异常

Exceptions raised in the child process, before the new program has started to execute, will be re-raised in the parent.在新程序开始执行之前,子进程中引发的异常将在父进程中重新引发。

The most common exception raised is OSError. 引发的最常见异常是OSErrorThis occurs, for example, when trying to execute a non-existent file. 例如,当试图执行不存在的文件时,就会发生这种情况。Applications should prepare for OSError exceptions. 应用程序应为OSError异常做好准备。Note that, when shell=True, OSError will be raised by the child only if the selected shell itself was not found. 注意,当shell=True时,只有在未找到所选shell本身时,子级才会引发OSErrorTo determine if the shell failed to find the requested application, it is necessary to check the return code or output from the subprocess.要确定shell是否未能找到请求的应用程序,需要检查子流程的返回代码或输出。

A ValueError will be raised if Popen is called with invalid arguments.如果使用无效参数调用Popen,将引发ValueError

check_call() and check_output() will raise CalledProcessError if the called process returns a non-zero return code.如果被调用的进程返回非零返回代码,check_call()check_output()将引发CalledProcessError

All of the functions and methods that accept a timeout parameter, such as call() and Popen.communicate() will raise TimeoutExpired if the timeout expires before the process exits.所有接受timeout参数的函数和方法,如call()Popen.communicate(),如果超时在进程退出之前过期,则会引发TimeoutExpired

Exceptions defined in this module all inherit from SubprocessError.此模块中定义的异常都继承自SubprocessError

New in version 3.3.版本3.3中新增。The SubprocessError base class was added.已添加SubprocessError基类。

Security Considerations安全注意事项

Unlike some other popen functions, this implementation will never implicitly call a system shell. 与其他一些popen函数不同,这个实现永远不会隐式调用系统shell。This means that all characters, including shell metacharacters, can safely be passed to child processes. 这意味着所有字符(包括外壳元字符)都可以安全地传递给子进程。If the shell is invoked explicitly, via shell=True, it is the application’s responsibility to ensure that all whitespace and metacharacters are quoted appropriately to avoid shell injection vulnerabilities. 如果通过shell=True显式调用shell,则应用程序有责任确保正确引用所有空格和元字符,以避免shell注入漏洞。On some platforms, it is possible to use shlex.quote() for this escaping.某些平台上,可以使用shlex.quote()进行这种转义。

Popen Objects

Instances of the Popen class have the following methods:Popen类的实例具有以下方法:

Popen.poll()

Check if child process has terminated. 检查子进程是否已终止。Set and return returncode attribute. 设置并返回returncode属性。Otherwise, returns None.否则,返回None

Popen.wait(timeout=None)

Wait for child process to terminate. 等待子进程终止。Set and return returncode attribute.设置并返回returncode属性。

If the process does not terminate after timeout seconds, raise a TimeoutExpired exception. 如果进程在timeout秒后未终止,则引发TimeoutExpired异常。It is safe to catch this exception and retry the wait.捕获此异常并重试等待是安全的。

Note

This will deadlock when using stdout=PIPE or stderr=PIPE and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data. 当使用stdout=PIPEstderr=PIPE时,这将导致死锁,并且子进程向管道生成足够的输出,从而阻止等待OS管道缓冲区接受更多数据。Use Popen.communicate() when using pipes to avoid that.使用管道时,请使用Popen.communicate()来避免这种情况。

Note

The function is implemented using a busy loop (non-blocking call and short sleeps). 该函数使用忙循环(非阻塞调用和短睡眠)实现。Use the asyncio module for an asynchronous wait: see asyncio.create_subprocess_exec.使用asyncio模块进行异步等待:请参阅asyncio.create_subprocess_exec

Changed in version 3.3:版本3.3中更改: timeout was added.已添加timeout

Popen.communicate(input=None, timeout=None)

Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. 与进程交互:将数据发送到stdin。从stdout和stderr读取数据,直到到达文件结尾。Wait for process to terminate and set the returncode attribute. 等待进程终止并设置returncode属性。The optional input argument should be data to be sent to the child process, or None, if no data should be sent to the child. 可选的input参数应该是要发送给子进程的数据,如果没有数据要发送给该子进程,则为NoneIf streams were opened in text mode, input must be a string. 如果流是以文本模式打开的,则input必须是字符串。Otherwise, it must be bytes.否则,它必须是字节。

communicate() returns a tuple (stdout_data, stderr_data). communicate()返回一个元组(stdout_data, stderr_data)The data will be strings if streams were opened in text mode; otherwise, bytes.如果流以文本模式打开,则数据将为字符串;否则为字节。

Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. 注意,如果要将数据发送到进程的stdin,则需要使用stdin=PIPE创建Popen对象。Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.类似地,要在结果元组中获得除None以外的任何内容,还需要提供stdout=PIPE和/或stderr=PIPE

If the process does not terminate after timeout seconds, a TimeoutExpired exception will be raised. 如果进程在timeout秒后未终止,将引发TimeoutExpired异常。Catching this exception and retrying communication will not lose any output.捕捉此异常并重试通信不会丢失任何输出。

The child process is not killed if the timeout expires, so in order to cleanup properly a well-behaved application should kill the child process and finish communication:如果超时过期,则不会终止子进程,因此为了正确清理,行为良好的应用程序应终止子进程并完成通信:

proc = subprocess.Popen(...)
try:
outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
proc.kill()
outs, errs = proc.communicate()

Note

The data read is buffered in memory, so do not use this method if the data size is large or unlimited.读取的数据缓冲在内存中,因此如果数据大小较大或不受限制,请不要使用此方法。

Changed in version 3.3:版本3.3中更改: timeout was added.已添加timeout

Popen.send_signal(signal)

Sends the signal signal to the child.向孩子发送信号signal

Do nothing if the process completed.如果过程完成,则不执行任何操作。

Note

On Windows, SIGTERM is an alias for terminate(). 在Windows上,SIGTERM是terminate()的别名。CTRL_C_EVENT and CTRL_BREAK_EVENT can be sent to processes started with a creationflags parameter which includes CREATE_NEW_PROCESS_GROUP.CTRL_C_EVENTCTRL_BREAK_EVENT可以发送到使用creationflags参数启动的进程,该参数包括CREATE_NEW_PROCESS_GROUP

Popen.terminate()

Stop the child. 阻止孩子。On POSIX OSs the method sends SIGTERM to the child. On Windows the Win32 API function TerminateProcess() is called to stop the child.在POSIX OS上,该方法将SIGTERM发送给子级。在Windows上,调用Win32 API函数TerminateProcess()来停止子进程。

Popen.kill()

Kills the child. 杀死了孩子。On POSIX OSs the function sends SIGKILL to the child. 在POSIX OS上,函数向子级发送SIGKILL。On Windows kill() is an alias for terminate().在Windows上,kill()terminate()的别名。

The following attributes are also available:以下属性也可用:

Popen.args

The args argument as it was passed to Popen – a sequence of program arguments or else a single string.传递给Popenargs参数是一系列程序参数或单个字符串。

New in version 3.3.版本3.3中新增。

Popen.stdin

If the stdin argument was PIPE, this attribute is a writeable stream object as returned by open(). 如果stdin参数是PIPE,则该属性是open()返回的可写流对象。If the encoding or errors arguments were specified or the universal_newlines argument was True, the stream is a text stream, otherwise it is a byte stream. 如果指定了encodingerrors参数,或者universal_newlines参数为True,则该流为文本流,否则为字节流。If the stdin argument was not PIPE, this attribute is None.如果stdin参数不是PIPE,则该属性为None

Popen.stdout

If the stdout argument was PIPE, this attribute is a readable stream object as returned by open(). 如果stdout参数为PIPE,则该属性是open()返回的可读流对象。Reading from the stream provides output from the child process. 从流读取提供子进程的输出。If the encoding or errors arguments were specified or the universal_newlines argument was True, the stream is a text stream, otherwise it is a byte stream. 如果指定了encodingerrors参数,或者universal_newlines参数为True,则该流为文本流,否则为字节流。If the stdout argument was not PIPE, this attribute is None.如果stdout参数不是PIPE,则此属性为None

Popen.stderr

If the stderr argument was PIPE, this attribute is a readable stream object as returned by open(). 如果stderr参数为PIPE,则该属性是open()返回的可读流对象。Reading from the stream provides error output from the child process. 从流读取提供子进程的错误输出。If the encoding or errors arguments were specified or the universal_newlines argument was True, the stream is a text stream, otherwise it is a byte stream. 如果指定了encodingerrors参数,或者universal_newlines参数为True,则该流为文本流,否则为字节流。If the stderr argument was not PIPE, this attribute is None.如果stderr参数不是PIPE,则此属性为None

Warning

Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.使用communicate()而不是.stdin.write.stdout.read.stderr.read,以避免由于任何其他OS管道缓冲区填满并阻塞子进程而导致死锁。

Popen.pid

The process ID of the child process.子进程的进程ID。

Note that if you set the shell argument to True, this is the process ID of the spawned shell.注意,如果将shell参数设置为True,则这是派生shell的进程ID。

Popen.returncode

The child return code, set by poll() and wait() (and indirectly by communicate()). 子返回代码,由poll()wait()设置(并由communicate()间接设置)。A None value indicates that the process hasn’t terminated yet.None值表示进程尚未终止。

A negative value -N indicates that the child was terminated by signal N负值-N表示孩子被信号N终止 (POSIX only).

Windows Popen Helpers

The STARTUPINFO class and following constants are only available on Windows.STARTUPINFO类和以下常量仅在Windows上可用。

classsubprocess.STARTUPINFO(*, dwFlags=0, hStdInput=None, hStdOutput=None, hStdError=None, wShowWindow=0, lpAttributeList=None)

Partial support of the Windows STARTUPINFO structure is used for Popen creation. Windows STARTUPINFO结构的部分支持用于Popen创建。The following attributes can be set by passing them as keyword-only arguments.以下属性可以通过将它们作为仅关键字参数传递来设置。

Changed in version 3.7:版本3.7中更改: Keyword-only argument support was added.添加了仅关键字参数支持。

dwFlags

A bit field that determines whether certain STARTUPINFO attributes are used when the process creates a window.一个位字段,用于确定进程创建窗口时是否使用某些STARTUPINFO属性。

si = subprocess.STARTUPINFO()
si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
hStdInput

If dwFlags specifies STARTF_USESTDHANDLES, this attribute is the standard input handle for the process. 如果dwFlags指定STARTF_USESTDHANDLES,则该属性是进程的标准输入句柄。If STARTF_USESTDHANDLES is not specified, the default for standard input is the keyboard buffer.如果未指定STARTF_USESTDHANDLES,则标准输入的默认值是键盘缓冲区。

hStdOutput

If dwFlags specifies STARTF_USESTDHANDLES, this attribute is the standard output handle for the process. 如果dwFlags指定STARTF_USESTDHANDLES,则该属性是进程的标准输出句柄。Otherwise, this attribute is ignored and the default for standard output is the console window’s buffer.否则,该属性将被忽略,标准输出的默认值是控制台窗口的缓冲区。

hStdError

If dwFlags specifies STARTF_USESTDHANDLES, this attribute is the standard error handle for the process. 如果dwFlags指定STARTF_USESTDHANDLES,则该属性是进程的标准错误句柄。Otherwise, this attribute is ignored and the default for standard error is the console window’s buffer.否则,该属性将被忽略,标准错误的默认值是控制台窗口的缓冲区。

wShowWindow

If dwFlags specifies STARTF_USESHOWWINDOW, this attribute can be any of the values that can be specified in the nCmdShow parameter for the ShowWindow function, except for SW_SHOWDEFAULT. 如果dwFlags指定STARTF_USESHOWWINDOW,则该属性可以是ShowWindow函数的nCmdShow参数中指定的任何值,但SW_SHOWDEFAULT除外。Otherwise, this attribute is ignored.否则,将忽略此属性。

SW_HIDE is provided for this attribute. 为该属性提供了SW_HIDEIt is used when Popen is called with shell=True.当使用shell=True调用Popen时使用。

lpAttributeList

A dictionary of additional attributes for process creation as given in STARTUPINFOEX, see UpdateProcThreadAttribute.STARTUPINFOEX中提供的用于流程创建的其他属性字典,请参阅UpdateProcThreadAttribute

Supported attributes:支持的属性:

handle_list

Sequence of handles that will be inherited. 将继承的句柄序列。close_fds must be true if non-empty.如果非空,close_fds必须为true

The handles must be temporarily made inheritable by os.set_handle_inheritable() when passed to the Popen constructor, else OSError will be raised with Windows error ERROR_INVALID_PARAMETER (87).当传递给Popen构造函数时,句柄必须暂时由os.set_handle_inheritable()继承,否则将引发OSError,并出现Windows错误ERROR_INVALID_PARAMETER(87)。

Warning

In a multithreaded process, use caution to avoid leaking handles that are marked inheritable when combining this feature with concurrent calls to other process creation functions that inherit all handles such as os.system(). 在多线程进程中,当将此功能与继承所有句柄的其他进程创建函数(如os.system())的并发调用相结合时,请小心避免泄漏标记为可继承的句柄。This also applies to standard handle redirection, which temporarily creates inheritable handles.这也适用于标准句柄重定向,它临时创建可继承句柄。

New in version 3.7.版本3.7中新增。

Windows Constants

The subprocess module exposes the following constants.subprocess模块公开以下常量。

subprocess.STD_INPUT_HANDLE

The standard input device. 标准输入设备。Initially, this is the console input buffer, CONIN$.最初,这是控制台输入缓冲区CONIN$

subprocess.STD_OUTPUT_HANDLE

The standard output device. 标准输出设备。Initially, this is the active console screen buffer, CONOUT$.最初,这是活动控制台屏幕缓冲区CONOUT$

subprocess.STD_ERROR_HANDLE

The standard error device. 标准错误设备。Initially, this is the active console screen buffer, CONOUT$.最初,这是活动控制台屏幕缓冲区CONOUT$

subprocess.SW_HIDE

Hides the window. 隐藏窗口。Another window will be activated.将激活另一个窗口。

subprocess.STARTF_USESTDHANDLES

Specifies that the STARTUPINFO.hStdInput, STARTUPINFO.hStdOutput, and STARTUPINFO.hStdError attributes contain additional information.指定STARTUPINFO.hStdInputSTARTUPINFO.hStdOutputSTARTUPINFO.hStdError属性包含其他信息。

subprocess.STARTF_USESHOWWINDOW

Specifies that the STARTUPINFO.wShowWindow attribute contains additional information.指定STARTUPINFO.wShowWindow属性包含其他信息。

subprocess.CREATE_NEW_CONSOLE

The new process has a new console, instead of inheriting its parent’s console (the default).新进程有一个新的控制台,而不是继承其父进程的控制台(默认)。

subprocess.CREATE_NEW_PROCESS_GROUP

A Popen creationflags parameter to specify that a new process group will be created. Popen creationflags参数,用于指定将创建新的流程组。This flag is necessary for using os.kill() on the subprocess.此标志对于在子进程上使用os.kill()是必需的。

This flag is ignored if CREATE_NEW_CONSOLE is specified.如果指定了CREATE_NEW_CONSOLE,则忽略此标志。

subprocess.ABOVE_NORMAL_PRIORITY_CLASS

A Popen creationflags parameter to specify that a new process will have an above average priority.Popencreationflags参数,用于指定新进程的优先级高于平均值。

New in version 3.7.版本3.7中新增。

subprocess.BELOW_NORMAL_PRIORITY_CLASS

A Popen creationflags parameter to specify that a new process will have a below average priority.Popen creationflags参数,用于指定新进程的优先级低于平均值。

New in version 3.7.版本3.7中新增。

subprocess.HIGH_PRIORITY_CLASS

A Popen creationflags parameter to specify that a new process will have a high priority.Popen creationflags参数,用于指定新进程将具有高优先级。

New in version 3.7.版本3.7中新增。

subprocess.IDLE_PRIORITY_CLASS

A Popen creationflags parameter to specify that a new process will have an idle (lowest) priority.Popen creationflags参数,用于指定新进程将具有空闲(最低)优先级。

New in version 3.7.版本3.7中新增。

subprocess.NORMAL_PRIORITY_CLASS

A Popen creationflags parameter to specify that a new process will have an normal priority. (default)Popen creationflags参数,用于指定新进程将具有正常优先级。(默认)

New in version 3.7.版本3.7中新增。

subprocess.REALTIME_PRIORITY_CLASS

A Popen creationflags parameter to specify that a new process will have realtime priority. Popen creationflags参数,用于指定新进程将具有实时优先级。You should almost never use REALTIME_PRIORITY_CLASS, because this interrupts system threads that manage mouse input, keyboard input, and background disk flushing. 您几乎不应该使用REALTIME_PRIORITY_CLASS,因为这会中断管理鼠标输入、键盘输入和后台磁盘刷新的系统线程。This class can be appropriate for applications that “talk” directly to hardware or that perform brief tasks that should have limited interruptions.该类适用于直接与硬件“对话”的应用程序,或执行应具有有限中断的简短任务的应用程序。

New in version 3.7.版本3.7中新增。

subprocess.CREATE_NO_WINDOW

A Popen creationflags parameter to specify that a new process will not create a window.Popen creationflags参数,用于指定新进程不会创建窗口。

New in version 3.7.版本3.7中新增。

subprocess.DETACHED_PROCESS

A Popen creationflags parameter to specify that a new process will not inherit its parent’s console. Popen creationflags参数,用于指定新进程不会继承其父进程的控制台。This value cannot be used with CREATE_NEW_CONSOLE.此值不能与CREATE_NEW_CONSOLE一起使用。

New in version 3.7.版本3.7中新增。

subprocess.CREATE_DEFAULT_ERROR_MODE

A Popen creationflags parameter to specify that a new process does not inherit the error mode of the calling process. Popen creationflags参数,用于指定新进程不继承调用进程的错误模式。Instead, the new process gets the default error mode. 相反,新进程将获得默认错误模式。This feature is particularly useful for multithreaded shell applications that run with hard errors disabled.此功能对于在禁用硬错误的情况下运行的多线程shell应用程序特别有用。

New in version 3.7.版本3.7中新增。

subprocess.CREATE_BREAKAWAY_FROM_JOB

A Popen creationflags parameter to specify that a new process is not associated with the job.Popen creationflags参数,用于指定新进程与作业不关联。

New in version 3.7.版本3.7中新增。

Older high-level API

Prior to Python 3.5, these three functions comprised the high level API to subprocess. 在Python 3.5之前,这三个函数构成了子流程的高级API。You can now use run() in many cases, but lots of existing code calls these functions.您现在可以在许多情况下使用run(),但许多现有代码都调用这些函数。

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs)

Run the command described by args. 运行args描述的命令。Wait for command to complete, then return the returncode attribute.等待命令完成,然后返回returncode属性。

Code needing to capture stdout or stderr should use run() instead:需要捕获stdout或stderr的代码应改用run()

run(...).returncode

To suppress stdout or stderr, supply a value of DEVNULL.要抑制stdout或stderr,请提供DEVNULL值。

The arguments shown above are merely some common ones. 上述论点只是一些常见的论点。The full function signature is the same as that of the Popen constructor - this function passes all supplied arguments other than timeout directly through to that interface.完整的函数签名与Popen构造函数的签名相同-此函数将所有提供的参数(超时除外)直接传递到该接口。

Note

Do not use stdout=PIPE or stderr=PIPE with this function. 不要将stdout=PIPEstderr=PIPE与此函数一起使用。The child process will block if it generates enough output to a pipe to fill up the OS pipe buffer as the pipes are not being read from.如果子进程向管道生成足够的输出以填充OS管道缓冲区(因为没有从中读取管道),则子进程将阻塞。

Changed in version 3.3:版本3.3中更改: timeout was added.已添加timeout

subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs)

Run command with arguments. Wait for command to complete. 使用参数运行命令。等待命令完成。If the return code was zero then return, otherwise raise CalledProcessError. 如果返回代码为零,则返回,否则引发CalledProcessErrorThe CalledProcessError object will have the return code in the returncode attribute. CalledProcessError对象将在returncode属性中具有返回代码。If check_call() was unable to start the process it will propagate the exception that was raised.如果check_call()无法启动进程,它将传播引发的异常。

Code needing to capture stdout or stderr should use run() instead:需要捕获stdoutstderr的代码应改用run()

run(..., check=True)

To suppress stdout or stderr, supply a value of DEVNULL.要抑制stdoutstderr,请提供DEVNULL值。

The arguments shown above are merely some common ones. 上述论点只是一些常见的论点。The full function signature is the same as that of the Popen constructor - this function passes all supplied arguments other than timeout directly through to that interface.完整的函数签名与Popen构造函数的签名相同-此函数将所有提供的参数(timeout除外)直接传递到该接口。

Note

Do not use stdout=PIPE or stderr=PIPE with this function. 不要将stdout=PIPEstderr=PIPE与此函数一起使用。The child process will block if it generates enough output to a pipe to fill up the OS pipe buffer as the pipes are not being read from.如果子进程向管道生成足够的输出以填充OS管道缓冲区(因为没有从中读取管道),则子进程将阻塞。

Changed in version 3.3:版本3.3中更改: timeout was added.已添加timeout

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, cwd=None, encoding=None, errors=None, universal_newlines=None, timeout=None, text=None, **other_popen_kwargs)

Run command with arguments and return its output.使用参数运行命令并返回其输出。

If the return code was non-zero it raises a CalledProcessError. 如果返回代码为非零,则引发CalledProcessErrorThe CalledProcessError object will have the return code in the returncode attribute and any output in the output attribute.CalledProcessError对象将在returncode属性中具有返回代码,在output属性中具有任何输出。

This is equivalent to:这相当于:

run(..., check=True, stdout=PIPE).stdout

The arguments shown above are merely some common ones. 上述论点只是一些常见的论点。The full function signature is largely the same as that of run() - most arguments are passed directly through to that interface. 完整的函数签名与run()的签名基本相同-大多数参数都直接传递到该接口。One API deviation from run() behavior exists: passing input=None will behave the same as input=b'' (or input='', depending on other arguments) rather than using the parent’s standard input file handle.存在一个与run()行为的API偏差:传递input=None将与input=b''(或input='',取决于其他参数)的行为相同,而不是使用父级的标准输入文件句柄。

By default, this function will return the data as encoded bytes. 默认情况下,此函数将以编码字节的形式返回数据。The actual encoding of the output data may depend on the command being invoked, so the decoding to text will often need to be handled at the application level.输出数据的实际编码可能取决于所调用的命令,因此通常需要在应用程序级别处理对文本的解码。

This behaviour may be overridden by setting text, encoding, errors, or universal_newlines to True as described in Frequently Used Arguments and run().此行为可以通过将textencodingerrorsuniversal_newlines设置为True来覆盖,如常用参数run()中所述。

To also capture standard error in the result, use stderr=subprocess.STDOUT:要在结果中捕获标准错误,请使用stderr=subprocess.STDOUT

>>> subprocess.check_output(
... "ls non_existent_file; exit 0",
... stderr=subprocess.STDOUT,
... shell=True)
'ls: non_existent_file: No such file or directory\n'

New in version 3.1.版本3.1中新增。

Changed in version 3.3:版本3.3中更改: timeout was added.已添加timeout

Changed in version 3.4:版本3.4中更改: Support for the input keyword argument was added.添加了对input关键字参数的支持。

Changed in version 3.6:版本3.6中更改: encoding and errors were added. 添加了encodingerrorsSee run() for details.有关详细信息,请参阅run()

New in version 3.7.版本3.7中新增。text was added as a more readable alias for universal_newlines.text被添加为universal_newlines的更可读别名。

Replacing Older Functions with the subprocess Modulesubprocess模块替换旧函数

In this section, “a becomes b” means that b can be used as a replacement for a.在本节中,“a变为b”意味着b可以用作a的替代品。

Note

All “a” functions in this section fail (more or less) silently if the executed program cannot be found; the “b” replacements raise OSError instead.如果找不到执行的程序,本节中的所有“a”函数都会(或多或少)无声地失败;替换为“b”会引发OSError

In addition, the replacements using check_output() will fail with a CalledProcessError if the requested operation produces a non-zero return code. 此外,如果请求的操作产生非零返回代码,则使用check_output()的替换将失败,并出现CalledProcessErrorThe output is still available as the output attribute of the raised exception.输出仍然可用作为引发的异常的output属性。

In the following examples, we assume that the relevant functions have already been imported from the subprocess module.在以下示例中,我们假设相关函数已经从subprocess模块导入。

Replacing /bin/sh shell command substitution替换/bin/sh shell命令替换

output=$(mycmd myarg)

becomes:变为:

output = check_output(["mycmd", "myarg"])

Replacing shell pipeline更换壳体管道

output=$(dmesg | grep hda)

becomes:变为:

p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]

The p1.stdout.close() call after starting the p2 is important in order for p1 to receive a SIGPIPE if p2 exits before p1.如果p2在p1之前退出,那么启动p2后的p1.stdout.close()调用对于p1接收SIGPIPE非常重要。

Alternatively, for trusted input, the shell’s own pipeline support may still be used directly:或者,对于可信输入,shell自己的管道支持仍然可以直接使用:

output=$(dmesg | grep hda)

becomes:变为:

output = check_output("dmesg | grep hda", shell=True)

Replacing 替换os.system()

sts = os.system("mycmd" + " myarg")
# becomes
retcode = call("mycmd" + " myarg", shell=True)

Notes:笔记:

  • Calling the program through the shell is usually not required.通常不需要通过shell调用程序。

  • The call() return value is encoded differently to that of os.system().call()返回值的编码与os.system()不同。

  • The os.system() function ignores SIGINT and SIGQUIT signals while the command is running, but the caller must do this separately when using the subprocess module.os.system()函数在命令运行时忽略SIGINT和SIGQUIT信号,但调用方在使用subprocess模块时必须单独执行此操作。

A more realistic example would look like this:更现实的例子如下:

try:
retcode = call("mycmd" + " myarg", shell=True)
if retcode < 0:
print("Child was terminated by signal", -retcode, file=sys.stderr)
else:
print("Child returned", retcode, file=sys.stderr)
except OSError as e:
print("Execution failed:", e, file=sys.stderr)

Replacing the os.spawn family更换os.spawn家族

P_NOWAIT example:例子:

pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
==>
pid = Popen(["/bin/mycmd", "myarg"]).pid

P_WAIT example:例子:

retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
==>
retcode = call(["/bin/mycmd", "myarg"])

Vector example:矢量示例:

os.spawnvp(os.P_NOWAIT, path, args)
==>
Popen([path] + args[1:])

Environment example:环境示例:

os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
==>
Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})

Replacing os.popen(), os.popen2(), os.popen3()替换os.popen()os.popen2()os.popen3()

(child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
==>
p = Popen(cmd, shell=True, bufsize=bufsize,
stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdin, child_stdout) = (p.stdin, p.stdout)
(child_stdin,
child_stdout,
child_stderr) = os.popen3(cmd, mode, bufsize)
==>
p = Popen(cmd, shell=True, bufsize=bufsize,
stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
(child_stdin,
child_stdout,
child_stderr) = (p.stdin, p.stdout, p.stderr)
(child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
==>
p = Popen(cmd, shell=True, bufsize=bufsize,
stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)

Return code handling translates as follows:返回代码处理如下:

pipe = os.popen(cmd, 'w')
...
rc = pipe.close()
if rc is not None and rc >> 8:
print("There were some errors")
==>
process = Popen(cmd, stdin=PIPE)
...
process.stdin.close()
if process.wait() != 0:
print("There were some errors")

Replacing functions from the popen2 module更换popen2模块中的功能

Note

If the cmd argument to popen2 functions is a string, the command is executed through /bin/sh. 如果popen2函数的cmd参数是字符串,则命令通过/bin/sh执行。If it is a list, the command is directly executed.如果是列表,则直接执行命令。

(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
==>
p = Popen("somestring", shell=True, bufsize=bufsize,
stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)
(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
==>
p = Popen(["mycmd", "myarg"], bufsize=bufsize,
stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)

popen2.Popen3 and popen2.Popen4 basically work as subprocess.Popen, except that:popen2.Popen3popen2.Popen4基本上作为subprocess.Popen工作,除了:

  • Popen raises an exception if the execution fails.如果执行失败,则Popen引发异常。

  • The capturestderr argument is replaced with the stderr argument.capturestderr参数被stderr变量替换。

  • stdin=PIPE and stdout=PIPE must be specified.必须指定stdin=PIPEstdout=PIPE

  • popen2 closes all file descriptors by default, but you have to specify close_fds=True with Popen to guarantee this behavior on all platforms or past Python versions.popen2默认关闭所有文件描述符,但您必须使用Popen指定close_fds=True,以保证在所有平台或以前的Python版本上都有这种行为。

Legacy Shell Invocation Functions旧Shell调用函数

This module also provides the following legacy functions from the 2.x commands module. 该模块还提供2.xcommands模块中的以下传统功能。These operations implicitly invoke the system shell and none of the guarantees described above regarding security and exception handling consistency are valid for these functions.这些操作隐式调用系统外壳,并且上述关于安全性和异常处理一致性的任何保证对这些功能都无效。

subprocess.getstatusoutput(cmd)

Return (exitcode, output) of executing cmd in a shell.在shell中执行cmd的返回(exitcode, output)

Execute the string cmd in a shell with Popen.check_output() and return a 2-tuple (exitcode, output). 使用Popen.check_output()在shell中执行字符串cmd,并返回一个2元组(exitcode, output)The locale encoding is used; see the notes on Frequently Used Arguments for more details.使用区域设置编码;有关详细信息,请参阅常用参数的注释。

A trailing newline is stripped from the output. 从输出中删除尾随换行符。The exit code for the command can be interpreted as the return code of subprocess. 命令的退出代码可以解释为子流程的返回代码。Example:例子:

>>> subprocess.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> subprocess.getstatusoutput('cat /bin/junk')
(1, 'cat: /bin/junk: No such file or directory')
>>> subprocess.getstatusoutput('/bin/junk')
(127, 'sh: /bin/junk: not found')
>>> subprocess.getstatusoutput('/bin/kill $$')
(-15, '')

Availability: POSIX & Windows.

Changed in version 3.3.4:版本3.3.4中更改: Windows support was added.已添加Windows支持。

The function now returns (exitcode, output) instead of (status, output) as it did in Python 3.3.3 and earlier. 该函数现在返回(exitcode,output),而不是Python 3.3.3和更早版本中的(status,output)。exitcode has the same value as returncode.exitcode的值与returncode的值相同。

subprocess.getoutput(cmd)

Return output (stdout and stderr) of executing cmd in a shell.返回shell中执行cmd的输出(stdout和stderr)。

Like getstatusoutput(), except the exit code is ignored and the return value is a string containing the command’s output. getstatusoutput()类似,除了退出代码被忽略,返回值是包含命令输出的字符串。Example:例子:

>>> subprocess.getoutput('ls /bin/ls')
'/bin/ls'

Availability: POSIX & Windows.

Changed in version 3.3.4:版本3.3.4中更改: Windows support added

Notes

Converting an argument sequence to a string on Windows在Windows上将参数序列转换为字符串

On Windows, an args sequence is converted to a string that can be parsed using the following rules (which correspond to the rules used by the MS C runtime):在Windows上,args序列被转换为可以使用以下规则(对应于MS C运行时使用的规则)解析的字符串:

  1. Arguments are delimited by white space, which is either a space or a tab.参数由空格分隔,空格或制表符。

  2. A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within. 由双引号包围的字符串被解释为单个参数,而不考虑其中包含的空格。A quoted string can be embedded in an argument.带引号的字符串可以嵌入参数中。

  3. A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark.前面有反斜杠的双引号被解释为文字双引号。

  4. Backslashes are interpreted literally, unless they immediately precede a double quotation mark.反斜杠按字面意思解释,除非它们紧接在双引号之前。

  5. If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal backslash. 如果反斜杠紧跟在双引号之前,则每对反斜杠都被解释为一个字面反斜杠。If the number of backslashes is odd, the last backslash escapes the next double quotation mark as described in rule 3.如果反斜杠的数量为奇数,则最后一个反斜杠将转义下一个双引号,如规则3所述。

See also

shlex

Module which provides function to parse and escape command lines.提供解析和转义命令行功能的模块。