subprocess
— Subprocess 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 324 – PEP 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 在Python 3.5中添加了run()
function was added in Python 3.5; if you need to retain compatibility with older versions, see the Older high-level API section.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.)(timeout、input、check和capture_output都不是。)If capture_output is true, stdout and stderr will be captured.如果capture_output为true
,则将捕获stdout和stderr。When used, the internal使用时,内部Popen
object is automatically created withstdout=PIPE
andstderr=PIPE
.Popen
对象将自动创建为stdout=PIPE
和stderr=PIPE
。The stdout and stderr arguments may not be supplied at the same time as capture_output.stdout和stderr参数不能与capture_output同时提供。If you wish to capture and combine both streams into one, use如果希望捕获两个流并将其合并为一个流,请使用stdout=PIPE和stdout=PIPE
andstderr=STDOUT
instead of capture_output.stderr=STDOUT
,而不是capture_output。The timeout argument is passed totimeout参数传递给Popen.communicate()
.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 toinput参数传递给Popen.communicate()
and thus to the subprocess’s stdin.Popen.communicate()
,从而传递给子进程的stdin。If used it must be a byte sequence, or a string if encoding or errors is specified or text is true.如果使用,则必须是字节序列,如果指定了encoding或errors或text为真,则必须为字符串。When used, the internal使用时,内部Popen
object is automatically created withstdin=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如果check为CalledProcessError
exception will be raised.true
,并且进程以非零退出代码退出,则将引发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如果指定了encoding或errors,或者text为io.TextIOWrapper
default.true
,则使用指定的encoding和errors或io.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如果env不是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.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添加了encoding和errors参数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参数。
-
class
subprocess.
CompletedProcess
¶ The return value fromrun()
, 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 signalN
(POSIX only).-N
表示子进程由信号N
终止(仅限POSIX)。
-
stdout
¶ Captured stdout from the child process.从子进程捕获标准输出。A bytes sequence, or a string if一个字节序列,或者一个字符串,如果使用编码、错误或text=True调用run()
was called with an encoding, errors, or text=True.run()
。如果未捕获stdout,则None
if stdout was not captured.None
。If you ran the process with如果使用stderr=subprocess.STDOUT
, stdout and stderr will be combined in this attribute, andstderr
will beNone
.stderr=subprocess.STDOUT
运行进程,则stdout和stderr将在此属性中组合,并且stderr
为None
。
-
stderr
¶ Captured stderr from the child process.已从子进程捕获stderr。A bytes sequence, or a string if一个字节序列,或者一个字符串,如果使用编码、错误或text=True调用run()
was called with an encoding, errors, or text=True.run()
。如果未捕获stderr,则为None
if stderr was not captured.None
。
-
check_returncode
()¶ If如果returncode
is non-zero, raise aCalledProcessError
.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 fileos.devnull
will be used.Popen
的stdin、stdout或stderr参数的特殊值,表示将使用特殊文件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.Popen
的stdin、stdout或stderr参数的特殊值,指示应该打开到标准流的管道。Most useful withPopen.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.Popen
的stderr参数的特殊值,指示标准错误应该与标准输出进入相同的句柄。
-
exception
subprocess.
SubprocessError
¶ Base class for all other exceptions from this module.此模块中所有其他异常的基类。New in version 3.3.版本3.3中新增。
-
exception
subprocess.
TimeoutExpired
¶ Subclass ofSubprocessError
, 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()
orcheck_output()
.run()
或check_output()
捕获)。Otherwise,否则,为None
.None
。
-
stderr
¶ Stderr output of the child process if it was captured by子进程的Stderr输出(如果它被run()
.run()
捕获)。Otherwise,否则,None
.None
。
New in version 3.3.版本3.3中新增。Changed in version 3.5:版本3.5中更改:stdout and stderr attributes added添加了stdout和stderr属性-
-
exception
subprocess.
CalledProcessError
¶ Subclass ofSubprocessError
, raised when a process run bycheck_call()
orcheck_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()
orcheck_output()
.run()
或check_output()
捕获)。Otherwise,否则,为None
.None
。
-
stderr
¶ Stderr output of the child process if it was captured by子进程的Stderr输出(如果它被run()
.run()
捕获)。Otherwise,否则,为None
.None
。
Changed in version 3.5:版本3.5中更改:stdout and stderr attributes added添加了stdout和stderr属性-
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如果传递单个字符串,则shell必须为True
(see below) or else the string must simply name the program to be executed without specifying any arguments.True
(见下文),否则字符串必须简单地命名要执行的程序,而不指定任何参数。
stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively.stdin、stdout和stderr分别指定执行程序的标准输入、标准输出和标准错误文件句柄。Valid values are有效值为PIPE
,DEVNULL
, an existing file descriptor (a positive integer), an existing file object with a valid file descriptor, andNone
.PIPE
、DEVNULL
、现有文件描述符(正整数)、具有有效文件描述符的现有文件对象和None
。PIPE
indicates that a new pipe to the child should be created.PIPE
指示应创建子级的新管道。DEVNULL
indicates that the special fileos.devnull
will be used.DEVNULL
表示将使用特殊文件os.devnull
。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此外,stderr可以是STDOUT
, which indicates that the stderr data from the child process should be captured into the same file handle as for stdout.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如果指定了encoding或errors,或者text(也称为universal_newlines)为io.TextIOWrapper
.true
,则将使用调用中指定的编码和错误或io.TextIOWrapper
的默认值以文本模式打开文件对象stdin、stdout和stderr。
For stdin, line ending characters对于stdin,输入中的行结束字符'\n'
in the input will be converted to the default line separatoros.linesep
.'\n'
将转换为默认的行分隔符os.linesep
。For stdout and stderr, all line endings in the output will be converted to对于stdout和stderr,输出中的所有行结尾都将转换为'\n'
.'\n'
。For more information see the documentation of the有关更多信息,请参阅io.TextIOWrapper
class when the newline argument to its constructor isNone
.io.TextIOWrapper
类的文档,当其构造函数的newline参数为None
时。
If text mode is not used, stdin, stdout and stderr will be opened as binary streams.如果不使用文本模式,则stdin、stdout和stderr将作为二进制流打开。No encoding or line ending conversion is performed.不执行编码或行尾转换。
New in version 3.6.版本3.6中新增。Added encoding and errors parameters.添加了encoding和errors参数。
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 objectsPopen.stdin
,Popen.stdout
andPopen.stderr
are not updated by thePopen.communicate()
method.Popen.communicate()
方法不会更新文件对象Popen.stdin
、Popen.stdout
和Popen.stderr
的换行符属性。
If shell is如果shell为True
, the specified command will be executed through the shell.True
,则指定的命令将通过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如果您使用Python主要是为了增强对大多数系统shell的控制流,并且仍然希望方便地访问其他shell功能,例如shell管道、文件名通配符、环境变量扩展和用户主目录的~
to a user’s home directory.~
扩展,那么这将非常有用。However, note that Python itself offers implementations of many shell-like features (in particular,然而,请注意,Python本身提供了许多类似于shell的功能(特别是glob
,fnmatch
,os.walk()
,os.path.expandvars()
,os.path.expanduser()
, andshutil
).glob
、fnmatch
、os.walk()
、os.path.expandvars()
、os.path.expanduser()
和shutil
)的实现。
Changed in version 3.3:版本3.3中更改:When universal_newlines is当universal_newlines为True
, the class uses the encodinglocale.getpreferredencoding(False)
instead oflocale.getpreferredencoding()
.True
时,该类使用编码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.它提供了很大的灵活性,因此开发人员能够处理方便功能未涵盖的不太常见的情况。
-
class
subprocess.
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在POSIX上,类使用os.execvpe()
-like behavior to execute the child program.os.execvpe()
类行为来执行子程序。On Windows, the class uses the Windows在Windows上,该类使用WindowsCreateProcess()
function.CreateProcess()
函数。The arguments toPopen
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.有关与默认行为的其他差异,请参阅shell和executable参数。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
, useshutil.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对于POSIX,请参阅os.execvpe()
, and note that when resolving or searching for the executable path, cwd overrides the current working directory and env can override thePATH
environment variable.os.execvpe()
,并注意在解析或搜索可执行路径时,cwd会覆盖当前工作目录,env会覆盖path环境变量。For Windows, see the documentation of the对于Windows,请参阅WinAPI CreateProcess的lpApplicationName和lpCommandLine参数的文档,并注意在使用shell=False解析或搜索可执行路径时,cwd不会覆盖当前工作目录,env也无法覆盖lpApplicationName
andlpCommandLine
parameters of WinAPICreateProcess
, and note that when resolving or searching for the executable path withshell=False
, cwd does not override the current working directory and env cannot override thePATH
environment variable.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如果shell为False
and a sequence containing path-like objects on POSIX.False
,args参数接受类路径对象,并且接受POSIX上包含路径类对象的序列。Changed in version 3.8:版本3.8中更改:args parameter accepts a path-like object if shell is如果shell为False
and a sequence containing bytes and path-like objects on Windows.False
,args参数接受类路径对象,并且在Windows上接受包含字节和路径类对象的序列。The shell argument (which defaults toshell参数(默认为False
) specifies whether to use the shell as the program to execute.False
)指定是否使用shell作为要执行的程序。If shell is如果shell为True
, it is recommended to pass args as a string rather than as a sequence.True
,建议将args作为字符串而不是序列传递。On POSIX with在shell=True
, the shell defaults to/bin/sh
.shell=True
的POSIX上,shell默认为/bin/sh
。If 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
, theCOMSPEC
environment variable specifies the default shell.shell=True
的Windows上,COMSPEC
环境变量指定默认shell。The only time you need to specify在Windows上,唯一需要指定shell=True
on Windows is when the command you wish to execute is built into the shell (e.g. dir or copy).shell=True
的时间是您希望执行的命令内置在shell中时(例如dir或copy)。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创建stdin/stdout/stderr管道文件对象时,bufsize将作为open()
function when creating the stdin/stdout/stderr pipe file objects:open()
函数的对应参数提供:0
means unbuffered (read and write are one system call and can return short)0
表示无缓冲区(读和写是一个系统调用,可以短返回)1
means line buffered (only usable ifuniversal_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在Python 3.2.4和3.3.1之前的版本中,它错误地默认为0
which was unbuffered and allowed short reads.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.stdin、stdout和stderr分别指定执行程序的标准输入、标准输出和标准错误文件句柄。Valid values are有效值为PIPE
,DEVNULL
, an existing file descriptor (a positive integer), an existing file object with a valid file descriptor, andNone
.PIPE
、DEVNULL
、现有文件描述符(正整数)、具有有效文件描述符的现有文件对象和None
。PIPE
indicates that a new pipe to the child should be created.PIPE
指示应创建子级的新管道。DEVNULL
indicates that the special fileos.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此外,stderr可以是STDOUT
, which indicates that the stderr data from the applications should be captured into the same file handle as for stdout.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
.RuntimeError
。The 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如果close_fds为0
,1
and2
will be closed before the child process is executed.true
,则在执行子进程之前,将关闭除0
、1
和2
之外的所有文件描述符。Otherwise when close_fds is false, file descriptors obey their inheritable flag as described in Inheritance of File Descriptors.否则,当close_fds为false
时,文件描述符将遵循其可继承标志,如文件描述符继承中所述。On Windows, if close_fds is true then no handles will be inherited by the child process unless explicitly passed in the在Windows上,如果close_fds为handle_list
element ofSTARTUPINFO.lpAttributeList
, or by standard handle redirection.true
,则子进程将不会继承句柄,除非在STARTUPINFO.lpAttributeList
的handle_list
元素中显式传递,或通过标准句柄重定向传递。Changed in version 3.2:版本3.2中更改:The default for close_fds was changed fromclose_fds的默认值从False
to what is described above.False
更改为上述值。Changed in version 3.7:版本3.7中更改:On Windows the default for close_fds was changed from在Windows上,重定向标准句柄时,close_fds的默认值从False
toTrue
when redirecting the standard handles.False
更改为True
。It’s now possible to set close_fds to现在可以在重定向标准句柄时将close_fds设置为True
when redirecting the standard handles.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提供任何pass_fds都会强制close_fds为True
.True
。(POSIX only)Changed in version 3.2:版本3.2中更改:The pass_fds parameter was added.已添加pass_fds参数。If cwd is not如果cwd不是None
, the function changes the working directory to cwd before executing the child.None
,则函数在执行子级之前将工作目录更改为cwd。cwd 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_signals为true
(默认值),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_session为true
,则在执行子流程之前,将在子流程中进行setsid()
系统调用。(POSIX only)Changed in version 3.2:版本3.2中更改: start_new_session was added.If group is not如果group不是None
, the setregid() system call will be made in the child process prior to the execution of the subprocess.None
,则在执行子流程之前,将在子流程中进行setregid()
系统调用。If the provided value is a string, it will be looked up via如果提供的值是字符串,则将通过grp.getgrnam()
and the value ingr_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如果extra_groups不是None
, the setgroups() system call will be made in the child process prior to the execution of the subprocess.None
,则在执行子流程之前,将在子流程中进行setgroups()
系统调用。Strings provided in extra_groups will be looked up viaextra_groups中提供的字符串将通过grp.getgrnam()
and the values ingr_gid
will be used.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如果user不是None
, the setreuid() system call will be made in the child process prior to the execution of the subprocess.None
,则在执行子流程之前,将在子流程中进行setreuid()
系统调用。If the provided value is a string, it will be looked up via如果提供的值是字符串,则将通过pwd.getpwnam()
and the value inpw_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如果env不是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.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在Windows上,为了运行并行程序集,指定的env必须包含有效的SystemRoot
.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.如果指定了encoding或errors,或者text为true
,则文件对象stdin、stdout和stderr将以文本模式打开,并带有指定的编码和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.添加了encoding和errors。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将是STARTUPINFO
object, which is passed to the underlyingCreateProcess
function.STARTUPINFO
对象,该对象将传递给基础CreateProcess
函数。creationflags, if given, can be one or more of the following flags:如果给定了creationflags,creationflags可以是以下一个或多个标志:pipesize can be used to change the size of the pipe when当PIPE
is used for stdin, stdout or stderr.PIPE
用于stdin
、stdout
或stderr
时,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中新增。Thepipesize
parameter was added.Popen objects are supported as context managers via thePopen对象通过with
statement: on exit, standard file descriptors are closed, and the process is waited for.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 eventPopen和此模块中使用它的其他函数使用参数subprocess.Popen
with argumentsexecutable
,args
,cwd
, andenv
.executable
、args
、cwd
和env
引发审核事件subprocess.Popen
。The value forargs
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如果子进程仍在运行,Popen析构函数现在会发出ResourceWarning
warning if the child process is still running.ResourceWarning
警告。Changed in version 3.8:版本3.8中更改:Popen can usePopen在某些情况下可以使用os.posix_spawn()
in some cases for better performance.os.posix_spawn()
以获得更好的性能。On Windows Subsystem for Linux and QEMU User Emulation, Popen constructor using在Windows Subsystem for Linux和QEMU User Emulation上,使用os.posix_spawn()
no longer raise an exception on errors like missing program, but the child process fails with a non-zeroreturncode
.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
. OSError
。This 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本身时,子级才会引发OSError
。To 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 所有接受timeout参数的函数和方法,如call()
and Popen.communicate()
will raise TimeoutExpired
if the timeout expires before the process exits.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如果进程在timeout秒后未终止,则引发TimeoutExpired
exception.TimeoutExpired
异常。It is safe to catch this exception and retry the wait.捕获此异常并重试等待是安全的。Note
This will deadlock when using当使用stdout=PIPE
orstderr=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=PIPE
或stderr=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: seeasyncio.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可选的input参数应该是要发送给子进程的数据,如果没有数据要发送给该子进程,则为None
, if no data should be sent to the child.None
。If 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,则需要使用stdin=PIPE
.stdin=PIPE
创建Popen对象。Similarly, to get anything other than类似地,要在结果元组中获得除None
in the result tuple, you need to givestdout=PIPE
and/orstderr=PIPE
too.None
以外的任何内容,还需要提供stdout=PIPE
和/或stderr=PIPE
。If the process does not terminate after timeout seconds, a如果进程在timeout秒后未终止,将引发TimeoutExpired
exception will be raised.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在Windows上,SIGTERM是terminate()
.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_EVENT
和CTRL_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在POSIX OS上,该方法将SIGTERM发送给子级。在Windows上,调用Win32 API函数TerminateProcess()
is called to stop the child.TerminateProcess()
来停止子进程。
-
Popen.
kill
()¶ Kills the child.杀死了孩子。On POSIX OSs the function sends SIGKILL to the child.在POSIX OS上,函数向子级发送SIGKILL。On Windows在Windows上,kill()
is an alias forterminate()
.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.Popen
的args参数是一系列程序参数或单个字符串。New in version 3.3.版本3.3中新增。
-
Popen.
stdin
¶ If the stdin argument was如果stdin参数是PIPE
, this attribute is a writeable stream object as returned byopen()
.PIPE
,则该属性是open()
返回的可写流对象。If the encoding or errors arguments were specified or the universal_newlines argument was如果指定了encoding或errors参数,或者universal_newlines参数为True
, the stream is a text stream, otherwise it is a byte stream.True
,则该流为文本流,否则为字节流。If the stdin argument was not如果stdin参数不是PIPE
, this attribute isNone
.PIPE
,则该属性为None
。
-
Popen.
stdout
¶ If the stdout argument was如果stdout参数为PIPE
, this attribute is a readable stream object as returned byopen()
.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如果指定了encoding或errors参数,或者universal_newlines参数为True
, the stream is a text stream, otherwise it is a byte stream.True
,则该流为文本流,否则为字节流。If the stdout argument was not如果stdout参数不是PIPE
, this attribute isNone
.PIPE
,则此属性为None
。
-
Popen.
stderr
¶ If the stderr argument was如果stderr参数为PIPE
, this attribute is a readable stream object as returned byopen()
.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如果指定了encoding或errors参数,或者universal_newlines参数为True
, the stream is a text stream, otherwise it is a byte stream.True
,则该流为文本流,否则为字节流。If the stderr argument was not如果stderr参数不是PIPE
, this attribute isNone
.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注意,如果将shell参数设置为True
, this is the process ID of the spawned shell.True
,则这是派生shell的进程ID。
-
Popen.
returncode
¶ The child return code, set by子返回代码,由poll()
andwait()
(and indirectly bycommunicate()
).poll()
和wait()
设置(并由communicate()
间接设置)。ANone
value indicates that the process hasn’t terminated yet.None
值表示进程尚未终止。A negative value负值-N
indicates that the child was terminated by signalN
-N
表示孩子被信号N
终止 (POSIX only).
Windows Popen Helpers¶
The STARTUPINFO
class and following constants are only available on Windows.STARTUPINFO
类和以下常量仅在Windows上可用。
-
class
subprocess.
STARTUPINFO
(*, dwFlags=0, hStdInput=None, hStdOutput=None, hStdError=None, wShowWindow=0, lpAttributeList=None)¶ Partial support of the Windows STARTUPINFO structure is used forWindows STARTUPINFO结构的部分支持用于Popen
creation.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
specifiesSTARTF_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
specifiesSTARTF_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
specifiesSTARTF_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
specifiesSTARTF_USESHOWWINDOW
, this attribute can be any of the values that can be specified in thenCmdShow
parameter for the ShowWindow function, except forSW_SHOWDEFAULT
.dwFlags
指定STARTF_USESHOWWINDOW
,则该属性可以是ShowWindow函数的nCmdShow参数中指定的任何值,但SW_SHOWDEFAULT
除外。Otherwise, this attribute is ignored.否则,将忽略此属性。为该属性提供了SW_HIDE
is provided for this attribute.SW_HIDE
。It is used when当使用Popen
is called withshell=True
.shell=True
调用Popen
时使用。
-
lpAttributeList
¶ A dictionary of additional attributes for process creation as given inSTARTUPINFOEX
, 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 thePopen
constructor, elseOSError
will be raised with Windows errorERROR_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
, andSTARTUPINFO.hStdError
attributes contain additional information.STARTUPINFO.hStdInput
、STARTUPINFO.hStdOutput
和STARTUPINFO.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
¶ APopen
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
¶ APopen
creationflags
parameter to specify that a new process will have an above average priority.Popen
creationflags
参数,用于指定新进程的优先级高于平均值。New in version 3.7.版本3.7中新增。
-
subprocess.
BELOW_NORMAL_PRIORITY_CLASS
¶ APopen
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
¶ APopen
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
¶ APopen
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
¶ APopen
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
¶ APopen
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
¶ APopen
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
¶ APopen
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
¶ APopen
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中新增。
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需要捕获stdout或stderr的代码应改用run()
instead:run()
:run(...).returncode
To suppress stdout or stderr, supply a value of要抑制stdout或stderr,请提供DEVNULL
.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
orstderr=PIPE
with this function.stdout=PIPE
或stderr=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
.CalledProcessError
。TheCalledProcessError
object will have the return code in thereturncode
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需要捕获stdout或stderr的代码应改用run()
instead:run()
:run(..., check=True)
To suppress stdout or stderr, supply a value of要抑制stdout或stderr,请提供DEVNULL
.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
orstderr=PIPE
with this function.stdout=PIPE
或stderr=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
.CalledProcessError
。TheCalledProcessError
object will have the return code in thereturncode
attribute and any output in theoutput
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: passinginput=None
will behave the same asinput=b''
(orinput=''
, 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此行为可以通过将text、encoding、errors或universal_newlines设置为True
as described in Frequently Used Arguments andrun()
.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.添加了encoding和errors。See有关详细信息,请参阅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
Module用subprocess
模块替换旧函数¶
subprocess
ModuleIn 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 如果找不到执行的程序,本节中的所有“a”函数都会(或多或少)无声地失败;替换为“b”会引发OSError
instead.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()
的替换将失败,并出现CalledProcessError
。The 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 如果p2在p1之前退出,那么启动p2后的p1.stdout.close()
call after starting the p2 is important in order for p1 to receive a SIGPIPE if p2 exits before p1.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调用程序。Thecall()
return value is encoded differently to that ofos.system()
.call()
返回值的编码与os.system()
不同。Theos.system()
function ignores SIGINT and SIGQUIT signals while the command is running, but the caller must do this separately when using thesubprocess
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
家族¶
os.spawn
familyP_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()
¶
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
模块中的功能¶
popen2
moduleNote
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.Popen3
和popen2.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
andstdout=PIPE
must be specified.stdin=PIPE
和stdout=PIPE
。popen2 closes all file descriptors by default, but you have to specifypopen2默认关闭所有文件描述符,但您必须使用close_fds=True
withPopen
to guarantee this behavior on all platforms or past Python versions.Popen
指定close_fds=True
,以保证在所有平台或以前的Python版本上都有这种行为。
Legacy Shell Invocation Functions旧Shell调用函数¶
This module also provides the following legacy functions from the 2.x 该模块还提供2.xcommands
module. commands
模块中的以下传统功能。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在shell中执行cmd的返回(exitcode, output)
of executing cmd in a shell.(exitcode, output)
。E
xecute 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 asreturncode
.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运行时使用的规则)解析的字符串:
Arguments are delimited by white space, which is either a space or a tab.参数由空格分隔,空格或制表符。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.带引号的字符串可以嵌入参数中。A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark.前面有反斜杠的双引号被解释为文字双引号。Backslashes are interpreted literally, unless they immediately precede a double quotation mark.反斜杠按字面意思解释,除非它们紧接在双引号之前。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.提供解析和转义命令行功能的模块。