🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
### 导航 - [索引](../genindex.xhtml "总目录") - [模块](../py-modindex.xhtml "Python 模块索引") | - [下一页](sched.xhtml "sched --- 事件调度器") | - [上一页](concurrent.futures.xhtml "concurrent.futures --- 启动并行任务") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) » - zh\_CN 3.7.3 [文档](../index.xhtml) » - [Python 标准库](index.xhtml) » - [并发执行](concurrency.xhtml) » - $('.inline-search').show(0); | # [`subprocess`](#module-subprocess "subprocess: Subprocess management.") --- 子进程管理 **源代码:** [Lib/subprocess.py](https://github.com/python/cpython/tree/3.7/Lib/subprocess.py) \[https://github.com/python/cpython/tree/3.7/Lib/subprocess.py\] - - - - - - [`subprocess`](#module-subprocess "subprocess: Subprocess management.") 模块允许你生成新的进程,连接它们的输入、输出、错误管道,并且获取它们的返回码。此模块打算代替一些老旧的模块与功能: ``` os.system os.spawn* ``` 在下面的段落中,你可以找到关于 [`subprocess`](#module-subprocess "subprocess: Subprocess management.") 模块如何代替这些模块和功能的相关信息。 参见 [**PEP 324**](https://www.python.org/dev/peps/pep-0324) \[https://www.python.org/dev/peps/pep-0324\] -- 提出 subprocess 模块的 PEP ## 使用 [`subprocess`](#module-subprocess "subprocess: Subprocess management.") 模块 推荐的调用子进程的方式是在任何它支持的用例中使用 [`run()`](#subprocess.run "subprocess.run") 函数。对于更进阶的用例,也可以使用底层的 [`Popen`](#subprocess.Popen "subprocess.Popen") 接口。 [`run()`](#subprocess.run "subprocess.run") 函数是在 Python 3.5 被添加的;如果你需要与旧版本保持兼容,查看 [Older high-level API](#call-function-trio) 段落。 `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*)运行被 *arg* 描述的指令。等待指令完成,然后返回一个 [`CompletedProcess`](#subprocess.CompletedProcess "subprocess.CompletedProcess") 示例。 以上显示的参数仅仅是最简单的一些,下面 [常用参数](#frequently-used-arguments) 描述(因此在缩写签名中使用仅关键字标示)。完整的函数头和 [`Popen`](#subprocess.Popen "subprocess.Popen") 的构造函数一样,此函数接受的大多数参数都被传递给该接口。(*timeout*, *input*, *check* 和 *capture\_output* 除外)。 If *capture\_output* is true, stdout and stderr will be captured. When used, the internal [`Popen`](#subprocess.Popen "subprocess.Popen") object is automatically created with `stdout=PIPE` and `stderr=PIPE`. The *stdout* and *stderr* arguments may not be supplied at the same time as *capture\_output*. If you wish to capture and combine both streams into one, use `stdout=PIPE` and `stderr=STDOUT`instead of *capture\_output*. *timeout* 参数将被传递给 [`Popen.communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate")。如果发生超时,子进程将被杀死并等待。 [`TimeoutExpired`](#subprocess.TimeoutExpired "subprocess.TimeoutExpired") 异常将在子进程中断后被抛出。 *input* 参数将被传递给 [`Popen.communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate") 以及子进程的标准输入. 如果使用此参数, 它必须是一个字节序列. 如果指定了 *encoding* 或 *errors* 或者将 *text* 设置为 `True`, 那么也可以是一个字符串. 当使用此参数时, 内部的 [`Popen`](#subprocess.Popen "subprocess.Popen") 对象将自动被创建, 伴随着设置 `stdin=PIPE`, 并且 *stdin* 可能不被使用. 如果 *check* 设为 True, 并且进程以非零状态码退出, 一个 [`CalledProcessError`](#subprocess.CalledProcessError "subprocess.CalledProcessError") 异常将被抛出. 这个异常的属性将设置为参数, 退出码, 以及标准输出和标准错误, 如果被捕获到. 如果 *encoding* 或者 *error* 被指定, 或者 *text* 被设为 True, 标准输入, 标准输出和标准错误的文件对象将通过指定的 *encoding* 和 *errors* 以文本模式打开, 否则以默认的 [`io.TextIOWrapper`](io.xhtml#io.TextIOWrapper "io.TextIOWrapper") 打开. *universal\_newline* 参数等同于 *text* 并且提供了向后兼容性. 默认情况下, 文件对象是以二进制模式打开的. 如果 *env* 不是 `None`, 它必须是一个字典, 为新的进程设置环境变量; 它用于替换继承的当前进程的环境的默认行为. 它将直接被传递给 [`Popen`](#subprocess.Popen "subprocess.Popen"). 例如: ``` >>> 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'') ``` 3\.5 新版功能. 在 3.6 版更改: 添加了 *encoding* 和 *errors* 形参. 在 3.7 版更改: 添加了 *text* 形参, 作为 *universal\_newlines* 的一个更好理解的别名. 添加了 *capture\_output* 形参. *class* `subprocess.``CompletedProcess`[`run()`](#subprocess.run "subprocess.run") 的返回值, 代表一个进程已经结束. `args`被用作启动进程的参数. 可能是一个列表或字符串. `returncode`子进程的退出状态码. 通常来说, 一个为 0 的退出码表示进程运行正常. 一个负值 `-N` 表示子进程被信号 `N` 中断 (仅 POSIX). `stdout`从子进程捕获到的标准输出. 一个字节序列, 或一个字符串, 如果 [`run()`](#subprocess.run "subprocess.run") 是设置了 *encoding*, *errors* 或者 `text=True` 来运行的. 如果未有捕获, 则为 `None`. 如果你通过 `stderr=subprocess.STDOUT` 运行, 标准输入和标准错误将被组合在一起, 并且 `stderr`` 将为 `None`. `stderr`捕获到的子进程的标准错误. 一个字节序列, 或者一个字符串, 如果 [`run()`](#subprocess.run "subprocess.run") 是设置了参数 *encoding*, *errors* 或者 `text=True` 运行的. 如果未有捕获, 则为 `None`. `check_returncode`()如果 [`returncode`](#subprocess.CompletedProcess.returncode "subprocess.CompletedProcess.returncode") 非零, 抛出 [`CalledProcessError`](#subprocess.CalledProcessError "subprocess.CalledProcessError"). 3\.5 新版功能. `subprocess.``DEVNULL`可被 [`Popen`](#subprocess.Popen "subprocess.Popen") 的 *stdin*, *stdout* 或者 *stderr* 参数使用的特殊值, 表示使用特殊文件 [`os.devnull`](os.xhtml#os.devnull "os.devnull"). 3\.3 新版功能. `subprocess.``PIPE`可被 [`Popen`](#subprocess.Popen "subprocess.Popen") 的 *stdin*, *stdout* 或者 *stderr* 参数使用的特殊值, 表示打开标准流的管道. 常用于 [`Popen.communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate"). `subprocess.``STDOUT`可被 [`Popen`](#subprocess.Popen "subprocess.Popen") 的 *stdin* , *stdout* 或者 *stderr* 参数使用的特殊值, 表示标准错误与标准输出使用同一句柄。 *exception* `subprocess.``SubprocessError`此模块的其他异常的基类。 3\.3 新版功能. *exception* `subprocess.``TimeoutExpired`[`SubprocessError`](#subprocess.SubprocessError "subprocess.SubprocessError") 的子类,等待子进程的过程中发生超时时被抛出。 `cmd`用于创建子进程的指令。 `timeout`超时秒数。 `output`子进程的输出, 如果被 [`run()`](#subprocess.run "subprocess.run") 或 [`check_output()`](#subprocess.check_output "subprocess.check_output") 捕获。否则为 `None`。 `stdout`对 output 的别名,对应的有 [`stderr`](#subprocess.TimeoutExpired.stderr "subprocess.TimeoutExpired.stderr")。 `stderr`子进程的标准错误输出,如果被 [`run()`](#subprocess.run "subprocess.run") 捕获。 否则为 `None`。 3\.3 新版功能. 在 3.5 版更改: 添加了 *stdout* 和 *stderr* 属性。 *exception* `subprocess.``CalledProcessError`[`SubprocessError`](#subprocess.SubprocessError "subprocess.SubprocessError") 的子类,当一个被 [`check_call()`](#subprocess.check_call "subprocess.check_call") 或 [`check_output()`](#subprocess.check_output "subprocess.check_output") 函数运行的子进程返回了非零退出码时被抛出。 `returncode`子进程的退出状态。如果程序由一个信号终止,这将会被设为一个负的信号码。 `cmd`用于创建子进程的指令。 `output`子进程的输出, 如果被 [`run()`](#subprocess.run "subprocess.run") 或 [`check_output()`](#subprocess.check_output "subprocess.check_output") 捕获。否则为 `None`。 `stdout`对 output 的别名,对应的有 [`stderr`](#subprocess.CalledProcessError.stderr "subprocess.CalledProcessError.stderr")。 `stderr`子进程的标准错误输出,如果被 [`run()`](#subprocess.run "subprocess.run") 捕获。 否则为 `None`。 在 3.5 版更改: 添加了 *stdout* 和 *stderr* 属性。 ### 常用参数 为了支持丰富的使用案例, [`Popen`](#subprocess.Popen "subprocess.Popen") 的构造函数(以及方便的函数)接受大量可选的参数。对于大多数典型的用例,许多参数可以被安全地留以它们的默认值。通常需要的参数有: > *args* 被所有调用需要,应当为一个字符串,或者一个程序参数序列。提供一个参数序列通常更好,它可以更小心地使用参数中的转义字符以及引用(例如允许文件名中的空格)。如果传递一个简单的字符串,则 *shell* 参数必须为 [`True`](constants.xhtml#True "True") (见下文)或者该字符串中将被运行的程序名必须用简单的命名而不指定任何参数。 > > *stdin*, *stdout* 和 *stderr* 分别指定了执行的程序的标准输入、输出和标准错误文件句柄。合法的值有 [`PIPE`](#subprocess.PIPE "subprocess.PIPE") 、 [`DEVNULL`](#subprocess.DEVNULL "subprocess.DEVNULL") 、 一个现存的文件描述符(一个正整数)、一个现存的文件对象以及 `None`。 [`PIPE`](#subprocess.PIPE "subprocess.PIPE") 表示应该新建一个对子进程的管道。 [`DEVNULL`](#subprocess.DEVNULL "subprocess.DEVNULL") 表示使用特殊的文件 [`os.devnull`](os.xhtml#os.devnull "os.devnull")。当使用默认设置 `None` 时,将不会进行重定向,子进程的文件流将继承自父进程。另外, *stderr* 可能为 [`STDOUT`](#subprocess.STDOUT "subprocess.STDOUT"),表示来自于子进程的标准错误数据应该被 *stdout* 相同的句柄捕获。 > > 如果 *encoding* 或 *errors* 被指定,或者 *text* (也名为 *universal\_newlines*)为真,则文件对象 *stdin* 、 *stdout* 与 *stderr* 将会使用在此次调用中指定的 *encoding* 和 *errors* 以文本模式打开或者为默认的 [`io.TextIOWrapper`](io.xhtml#io.TextIOWrapper "io.TextIOWrapper")。 > > 当构造函数的 *newline* 参数为 `None` 时。对于 *stdin*, 输入的换行符 `'\n'` 将被转换为默认的换行符 [`os.linesep`](os.xhtml#os.linesep "os.linesep")。对于 *stdout* 和 *stderr*, 所有输出的换行符都被转换为 `'\n'`。更多信息,查看 [`io.TextIOWrapper`](io.xhtml#io.TextIOWrapper "io.TextIOWrapper") 类的文档。 > > 如果文本模式未被使用, *stdin*, *stdout* 和 *stderr* 将会以二进制流模式打开。没有编码与换行符转换发生。 > > 3\.6 新版功能: 添加了 *encoding* 和 *errors* 形参。 > > > > 3\.7 新版功能: 添加了 *text* 形参作为 *universal\_newlines* 的别名。 > > > > 注解 > > 文件对象 [`Popen.stdin`](#subprocess.Popen.stdin "subprocess.Popen.stdin") 、 [`Popen.stdout`](#subprocess.Popen.stdout "subprocess.Popen.stdout") 和 [`Popen.stderr`](#subprocess.Popen.stderr "subprocess.Popen.stderr") 的换行符属性不会被 [`Popen.communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate") 方法更新。 > > > > 如果 *shell* 设为 `True`,,则使用 shell 执行指定的指令。如果您主要使用 Python 增强的控制流(它比大多数系统 shell 提供的强大),并且仍然希望方便地使用其他 shell 功能,如 shell 管道、文件通配符、环境变量展开以及 `~` 展开到用户家目录,这将非常有用。但是,注意 Python 自己也实现了许多类似 shell 的特性(例如 [`glob`](glob.xhtml#module-glob "glob: Unix shell style pathname pattern expansion."), [`fnmatch`](fnmatch.xhtml#module-fnmatch "fnmatch: Unix shell style filename pattern matching."), [`os.walk()`](os.xhtml#os.walk "os.walk"), [`os.path.expandvars()`](os.path.xhtml#os.path.expandvars "os.path.expandvars"), [`os.path.expanduser()`](os.path.xhtml#os.path.expanduser "os.path.expanduser") 和 [`shutil`](shutil.xhtml#module-shutil "shutil: High-level file operations, including copying."))。 > > 在 3.3 版更改: 当 *universal\_newline* 被设为 `True`,则类使用 [`locale.getpreferredencoding(False)`](locale.xhtml#locale.getpreferredencoding "locale.getpreferredencoding") 编码来代替 `locale.getpreferredencoding()`。关于它们的区别的更多信息,见 [`io.TextIOWrapper`](io.xhtml#io.TextIOWrapper "io.TextIOWrapper")。 > > > > 注解 > > 在使用 `shell=True` 之前, 请阅读 [Security Considerations](#security-considerations) 段落。 这些选项以及所有其他选项在 [`Popen`](#subprocess.Popen "subprocess.Popen") 构造函数文档中有更详细的描述。 ### Popen 构造函数 此模块的底层的进程创建与管理由 [`Popen`](#subprocess.Popen "subprocess.Popen") 类处理。它提供了很大的灵活性,因此开发者能够处理未被便利函数覆盖的不常见用例。 *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=()*, *\**, *encoding=None*, *errors=None*, *text=None*)在一个新的进程中执行子程序。在 POSIX,此类使用类似于 [`os.execvp()`](os.xhtml#os.execvp "os.execvp") 的行为来执行子程序。在 Windows,此类使用了 Windows `CreateProcess()` 函数。 [`Popen`](#subprocess.Popen "subprocess.Popen") 的参数如下: *args* 应当是一个程序的参数列表或者一个简单的字符串。默认情况下,如果 *args* 是一个序列,将运行的程序是此序列的第一项。如果 *args* 是一个字符串,解释是平台相关的,如下所述。有关默认行为的其他差异,见 *shell* 和 *executable* 参数。除非另有说明,推荐将 *args* 作为序列传递。 在 POSIX,如果 *args* 是一个字符串,此字符串被作为将被执行的程序的命名或路径解释。但是,只有在不传递任何参数给程序的情况下才能这么做。 注解 [`shlex.split()`](shlex.xhtml#shlex.split "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! ``` 特别注意,由 shell 中的空格分隔的选项(例如 *-input*)和参数(例如 *eggs.txt* )位于分开的列表元素中,而在需要时使用引号或反斜杠转义的参数在 shell (例如包含空格的文件名或上面显示的 *echo* 命令)是单独的列表元素。 在 Windows,如果 *args* 是一个序列,他将通过一个在 [Converting an argument sequence to a string on Windows](#converting-argument-sequence) 描述的方式被转换为一个字符串。这是因为底层的 `CreateProcess()` 只处理字符串。 参数 *shell* (默认为 `False`)指定是否使用 shell 执行程序。如果 *shell* 为 `True`,更推荐将 *args* 作为字符串传递而非序列。 在 POSIX,当 `shell=True`, shell 默认为 `/bin/sh`。如果 *args* 是一个字符串,此字符串指定将通过 shell 执行的命令。这意味着字符串的格式必须和在命令提示符中所输入的完全相同。这包括,例如,引号和反斜杠转义包含空格的文件名。如果 *args* 是一个序列,第一项指定了命令,另外的项目将作为传递给 shell (而非命令) 的参数对待。也就是说, [`Popen`](#subprocess.Popen "subprocess.Popen") 等同于: ``` Popen(['/bin/sh', '-c', args[0], args[1], ...]) ``` 在 Windows,使用 `shell=True`,环境变量 `COMSPEC` 指定了默认 shell。在 Windows 你唯一需要指定 `shell=True` 的情况是你想要执行内置在 shell 中的命令(例如 **dir** 或者 **copy**)。在运行一个批处理文件或者基于控制台的可执行文件时,不需要 `shell=True`。 注解 在使用 `shell=True` 之前, 请阅读 [Security Considerations](#security-considerations) 段落。 *bufsize* 将在 [`open()`](functions.xhtml#open "open") 函数创建了 stdin/stdout/stderr 管道文件对象时作为对应的参数供应: - `0` 表示不使用缓冲区 (读取与写入是一个系统调用并且可以返回短内容) - `1` 表示行缓冲(只有 `universal_newlines=True` 时才有用,例如,在文本模式中) - 任何其他正值表示使用一个约为对应大小的缓冲区 - 负的 *bufsize* (默认)表示使用系统默认的 io.DEFAULT\_BUFFER\_SIZE。 在 3.3.1 版更改: *bufsize* 现在默认为 -1 来启用缓冲,以符合大多数代码所期望的行为。在 Python 3.2.4 和 3.3.1 之前的版本中,它错误地将默认值设为了为 `0`,这是无缓冲的并且允许短读取。这是无意的,并且与大多数代码所期望的 Python 2 的行为不一致。 *executable* 参数指定一个要执行的替换程序。这很少需要。当 `shell=True`, *executable* 替换 *args* 指定运行的程序。但是,原始的 *args* 仍然被传递给程序。大多数程序将被 *args* 指定的程序作为命令名对待,这可以与实际运行的程序不同。在 POSIX, *args* 名作为实际调用程序中可执行文件的显示名称,例如 **ps**。如果 `shell=True`,在 POSIX, *executable* 参数指定用于替换默认 shell `/bin/sh` 的 shell。 *stdin*, *stdout* 和 *stderr* 分别指定被运行的程序的标准输入、输出和标准错误的文件句柄。合法的值有 [`PIPE`](#subprocess.PIPE "subprocess.PIPE") , [`DEVNULL`](#subprocess.DEVNULL "subprocess.DEVNULL") , 一个存在的文件描述符(一个正整数),一个存在的 [文件对象](../glossary.xhtml#term-file-object) 以及 `None`。 [`PIPE`](#subprocess.PIPE "subprocess.PIPE") 表示应创建一个新的对子进程的管道。 [`DEVNULL`](#subprocess.DEVNULL "subprocess.DEVNULL") 表示使用特殊的 [`os.devnull`](os.xhtml#os.devnull "os.devnull") 文件。使用默认的 `None`,则不进行成定向;子进程的文件流将继承自父进程。另外, *stderr* 可设为 [`STDOUT`](#subprocess.STDOUT "subprocess.STDOUT"),表示应用程序的标准错误数据应和标准输出一同捕获。 如果 *preexec\_fn* 被设为一个可调用对象,此对象将在子进程刚创建时被调用。(仅 POSIX) 警告 *preexec\_fn* 形参在应用程序中存在多线程时是不安全的。子进程在调用前可能死锁。如果你必须使用它,保持警惕!最小化你调用的库的数量。 注解 如果你需要修改子进程环境,使用 *env* 形参而非在 *preexec\_fn* 中进行。 *start\_new\_session* 形参可以代替之前常用的 *preexec\_fn* 来在子进程中调用 os.setsid()。 如果 *close\_fds* 为真,所有文件描述符除了 `0`, `1`, `2` 之外都会在子进程执行前关闭。而当 *close\_fds* 为假时,文件描述符遵守它们继承的标志,如 [Inheritance of File Descriptors](os.xhtml#fd-inheritance) 所述。 在 Windows,如果 *close\_fds* 为真, 则子进程不会继承任何句柄,除非在 `STARTUPINFO.IpAttributeList` 的 `handle_list` 的键中显式传递,或者通过标准句柄重定向传递。 在 3.2 版更改: *close\_fds* 的默认值已经从 [`False`](constants.xhtml#False "False") 修改为上述值。 在 3.7 版更改: 在 Windows,当重定向标准句柄时 *close\_fds* 的默认值从 [`False`](constants.xhtml#False "False") 变为 [`True`](constants.xhtml#True "True")。现在重定向标准句柄时有可能设置 *close\_fds* 为 [`True`](constants.xhtml#True "True")。(标准句柄指三个 stdio 的句柄) *pass\_fds* 是一个可选的在父子进程间保持打开的文件描述符序列。提供任何 *pass\_fds* 将强制 *close\_fds* 为 [`True`](constants.xhtml#True "True")。(仅 POSIX) 3\.2 新版功能: 加入了 *pass\_fds* 形参。 如果 *cwd* 不为 `None`,此函数在执行子进程前改变当前工作目录为 *cwd*。 *cwd* 可以为一个 [`str`](stdtypes.xhtml#str "str") 和 [path-like](../glossary.xhtml#term-path-like-object) 对象。特别要注意,当可执行文件的路径为相对路径时,此函数按相对于 *cwd* 的路径来寻找 *executable* (或者 *args* 的第一项)。 在 3.6 版更改: *cwd* 形参接受一个 [path-like object](../glossary.xhtml#term-path-like-object)。 如果 *restore\_signals* 为 true(默认值),则 Python 设置为 SIG\_IGN 的所有信号将在 exec 之前的子进程中恢复为 SIG\_DFL。目前,这包括 SIGPIPE ,SIGXFZ 和 SIGXFSZ 信号。 (仅 POSIX) 在 3.2 版更改: *restore\_signals* 被加入。 如果 *start\_new\_session* 为 true,则 setsid() 系统调用将在子进程执行之前被执行。(仅 POSIX) 在 3.2 版更改: *start\_new\_session* 被添加。 如果 *env* 不为 `None`,则必须为一个为新进程定义了环境变量的字典;这些用于替换继承的当前进程环境的默认行为。 注解 如果指定, *env* 必须提供所有被子进程需求的变量。在 Windows,为了运行一个 [side-by-side assembly](https://en.wikipedia.org/wiki/Side-by-Side_Assembly) \[https://en.wikipedia.org/wiki/Side-by-Side\_Assembly\] ,指定的 *env* **必须** 包含一个有效的 `SystemRoot`。 如果 *encoding* 或 *errors* 被指定,或者 *text* 为 true,则文件对象 *stdin*, *stdout* 和 *stderr* 将会以指定的编码和 *errors* 以文本模式打开,如同 [常用参数](#frequently-used-arguments) 所述。 *universal\_newlines* 参数等同于 *text* 并且提供向后兼容性。默认情况下,文件对象都以二进制模式打开。 3\.6 新版功能: *encoding* 和 *errors* 被添加。 3\.7 新版功能: *text* 作为 *universal\_newlines* 的一个更具可读性的别名被添加。 如果给出, *startupinfo* 将是一个将被传递给底层的 `CreateProcess` 函数的 [`STARTUPINFO`](#subprocess.STARTUPINFO "subprocess.STARTUPINFO") 对象。 *creationflags*,如果给出,可以是一个或多个以下标志之一: > - [`CREATE_NEW_CONSOLE`](#subprocess.CREATE_NEW_CONSOLE "subprocess.CREATE_NEW_CONSOLE") > - [`CREATE_NEW_PROCESS_GROUP`](#subprocess.CREATE_NEW_PROCESS_GROUP "subprocess.CREATE_NEW_PROCESS_GROUP") > - [`ABOVE_NORMAL_PRIORITY_CLASS`](#subprocess.ABOVE_NORMAL_PRIORITY_CLASS "subprocess.ABOVE_NORMAL_PRIORITY_CLASS") > - [`BELOW_NORMAL_PRIORITY_CLASS`](#subprocess.BELOW_NORMAL_PRIORITY_CLASS "subprocess.BELOW_NORMAL_PRIORITY_CLASS") > - [`HIGH_PRIORITY_CLASS`](#subprocess.HIGH_PRIORITY_CLASS "subprocess.HIGH_PRIORITY_CLASS") > - [`IDLE_PRIORITY_CLASS`](#subprocess.IDLE_PRIORITY_CLASS "subprocess.IDLE_PRIORITY_CLASS") > - [`NORMAL_PRIORITY_CLASS`](#subprocess.NORMAL_PRIORITY_CLASS "subprocess.NORMAL_PRIORITY_CLASS") > - [`REALTIME_PRIORITY_CLASS`](#subprocess.REALTIME_PRIORITY_CLASS "subprocess.REALTIME_PRIORITY_CLASS") > - [`CREATE_NO_WINDOW`](#subprocess.CREATE_NO_WINDOW "subprocess.CREATE_NO_WINDOW") > - [`DETACHED_PROCESS`](#subprocess.DETACHED_PROCESS "subprocess.DETACHED_PROCESS") > - [`CREATE_DEFAULT_ERROR_MODE`](#subprocess.CREATE_DEFAULT_ERROR_MODE "subprocess.CREATE_DEFAULT_ERROR_MODE") > - [`CREATE_BREAKAWAY_FROM_JOB`](#subprocess.CREATE_BREAKAWAY_FROM_JOB "subprocess.CREATE_BREAKAWAY_FROM_JOB") Popen 对象支持通过 [`with`](../reference/compound_stmts.xhtml#with) 语句作为上下文管理器,在退出时关闭文件描述符并等待进程: ``` with Popen(["ifconfig"], stdout=PIPE) as proc: log.write(proc.stdout.read()) ``` 在 3.2 版更改: 添加了上下文管理器支持。 在 3.6 版更改: 现在,如果 Popen 析构时子进程仍然在运行,则析构器会发送一个 [`ResourceWarning`](exceptions.xhtml#ResourceWarning "ResourceWarning") 警告。 ### 异常 在子进程中抛出的异常,在新的进程开始执行前,将会被再次在父进程中抛出。 最常见的被抛出异常是 [`OSError`](exceptions.xhtml#OSError "OSError")。例如,当尝试执行一个不存在的文件时就会发生。应用程序需要为 [`OSError`](exceptions.xhtml#OSError "OSError") 异常做好准备。 如果 [`Popen`](#subprocess.Popen "subprocess.Popen") 调用时有无效的参数,则一个 [`ValueError`](exceptions.xhtml#ValueError "ValueError") 将被抛出。 `check_all()` 与 [`check_output()`](#subprocess.check_output "subprocess.check_output") 在调用的进程返回非零退出码时将抛出 [`CalledProcessError`](#subprocess.CalledProcessError "subprocess.CalledProcessError")。 所有接受 *timeout* 形参的函数与方法,例如 [`call()`](#subprocess.call "subprocess.call") 和 [`Popen.communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate") 将会在进程退出前超时到期时抛出 [`TimeoutExpired`](#subprocess.TimeoutExpired "subprocess.TimeoutExpired")。 此模块中定义的异常都继承自 [`SubprocessError`](#subprocess.SubprocessError "subprocess.SubprocessError")。 > 3\.3 新版功能: 基类 [`SubprocessError`](#subprocess.SubprocessError "subprocess.SubprocessError") 被添加。 ## 安全考量 不像一些其他的 popen 功能,此实现绝不会隐式调用一个系统 shell。这意味着任何字符,包括 shell 元字符,可以安全地被传递给子进程。如果 shell 被明确地调用,通过 `shell=True` 设置,则确保所有空白字符和元字符被恰当地包裹在引号内以避免 [shell 注入](https://en.wikipedia.org/wiki/Shell_injection#Shell_injection) \[https://en.wikipedia.org/wiki/Shell\_injection#Shell\_injection\] 漏洞就由应用程序负责了。 当使用 `shell=True`, [`shlex.quote()`](shlex.xhtml#shlex.quote "shlex.quote") 函数可以作为在将被用于构造 shell 指令的字符串中转义空白字符以及 shell 元字符的方案。 ## Popen 对象 [`Popen`](#subprocess.Popen "subprocess.Popen") 类的实例拥有以下方法: `Popen.``poll`()检查子进程是否已被终止。设置并返回 [`returncode`](#subprocess.Popen.returncode "subprocess.Popen.returncode") 属性。否则返回 `None`。 `Popen.``wait`(*timeout=None*)等待子进程被终止。设置并返回 [`returncode`](#subprocess.Popen.returncode "subprocess.Popen.returncode") 属性。 如果进程在 *timeout* 秒后未中断,抛出一个 [`TimeoutExpired`](#subprocess.TimeoutExpired "subprocess.TimeoutExpired") 异常,可以安全地捕获此异常并重新等待。 注解 当 `stdout=PIPE` 或者 `stderr=PIPE` 并且子进程产生了足以阻塞 OS 管道缓冲区接收更多数据的输出到管道时,将会发生死锁。当使用管道时用 [`Popen.communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate") 来规避它。 注解 此函数使用了一个 busy loop (非阻塞调用以及短睡眠) 实现。使用 [`asyncio`](asyncio.xhtml#module-asyncio "asyncio: Asynchronous I/O.") 模块进行异步等待: 参阅 [`asyncio.create_subprocess_exec`](asyncio-subprocess.xhtml#asyncio.create_subprocess_exec "asyncio.create_subprocess_exec")。 在 3.3 版更改: *timeout* 被添加 `Popen.``communicate`(*input=None*, *timeout=None*)与进程交互:向 stdin 传输数据。从 stdout 和 stderr 读取数据,直到文件结束符。等待进程终止。可选的 *input* 参数应当未被传输给子进程的数据,如果没有数据应被传输给子进程则为 `None`。如果流以文本模式打开, *input* 必须为字符串。否则,它必须为字节。 [`communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate") 返回一个 `(stdout_data, stderr_data)` 元组。如果文件以文本模式打开则为字符串;否则字节。 注意如果你想要向进程的 stdin 传输数据,你需要通过 `stdin=PIPE` 创建此 Popen 对象。类似的,要从结果元组获取任何非 `None` 值,你同样需要设置 `stdout=PIPE` 或者 `stderr=PIPE`。 如果进程在 *timeout* 秒后未终止,一个 [`TimeoutExpired`](#subprocess.TimeoutExpired "subprocess.TimeoutExpired") 异常将被抛出。捕获此异常并重新等待将不会丢失任何输出。 如果超时到期,子进程不会被杀死,所以为了正确清理一个行为良好的应用程序应该杀死子进程并完成通讯。 ``` proc = subprocess.Popen(...) try: outs, errs = proc.communicate(timeout=15) except TimeoutExpired: proc.kill() outs, errs = proc.communicate() ``` 注解 内存里数据读取是缓冲的,所以如果数据尺寸过大或无限,不要使用此方法。 在 3.3 版更改: *timeout* 被添加 `Popen.``send_signal`(*signal*)将信号 *signal* 发送给子进程。 注解 在 Windows, SIGTERM 是一个 [`terminate()`](#subprocess.Popen.terminate "subprocess.Popen.terminate") 的别名。 CTRL\_C\_EVENT 和 CTRL\_BREAK\_EVENT 可以被发送给以包含 `CREATE_NEW_PROCESS` 的 *creationflags* 形参启动的进程。 `Popen.``terminate`()停止子进程。在 Posix 操作系统上,此方法发送 SIGTERM。在 Windows,调用 Win32 API 函数 `TerminateProcess()` 来停止子进程。 `Popen.``kill`()杀死子进程。在 Posix 操作系统上,此函数给子进程发送 SIGKILL 信号。在 Windows 上, [`kill()`](#subprocess.Popen.kill "subprocess.Popen.kill") 是 [`terminate()`](#subprocess.Popen.terminate "subprocess.Popen.terminate") 的别名。 以下属性也是可用的: `Popen.``args`*args* 参数传递给 [`Popen`](#subprocess.Popen "subprocess.Popen") -- 一个程序参数的序列或者一个简单字符串。 3\.3 新版功能. `Popen.``stdin`如果 *stdin* 参数为 [`PIPE`](#subprocess.PIPE "subprocess.PIPE"),此属性是一个类似 [`open()`](functions.xhtml#open "open") 返回的可写的流对象。如果 *encoding* 或 *errors* 参数被指定或者 *universal\_newlines* 参数为 `True`,则此流是一个文本流,否则是字节流。如果 *stdin* 参数非 [`PIPE`](#subprocess.PIPE "subprocess.PIPE"), 此属性为 `None`。 `Popen.``stdout`如果 *stdout* 参数是 [`PIPE`](#subprocess.PIPE "subprocess.PIPE"),此属性是一个类似 [`open()`](functions.xhtml#open "open") 返回的可读流。从流中读取子进程提供的输出。如果 *encoding* 或 *errors* 参数被指定或者 *universal\_newlines* 参数为 `True`,此流为文本流,否则为字节流。如果 *stdout* 参数非 [`PIPE`](#subprocess.PIPE "subprocess.PIPE"),此属性为 `None`。 `Popen.``stderr`如果 *stderr* 参数是 [`PIPE`](#subprocess.PIPE "subprocess.PIPE"),此属性是一个类似 [`open()`](functions.xhtml#open "open") 返回的可读流。从流中读取子进程提供的输出。如果 *encoding* 或 *errors* 参数被指定或者 *universal\_newlines* 参数为 `True`,此流为文本流,否则为字节流。如果 *stderr* 参数非 [`PIPE`](#subprocess.PIPE "subprocess.PIPE"),此属性为 `None`。 警告 使用 [`communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate") 而非 [`.stdin.write`](#subprocess.Popen.stdin "subprocess.Popen.stdin"), [`.stdout.read`](#subprocess.Popen.stdout "subprocess.Popen.stdout") 或者 [`.stderr.read`](#subprocess.Popen.stderr "subprocess.Popen.stderr") 来避免由于任意其他 OS 管道缓冲区被子进程填满阻塞而导致的死锁。 `Popen.``pid`子进程的进程号。 注意如果你设置了 *shell* 参数为 `True`,则这是生成的子 shell 的进程号。 `Popen.``returncode`此进程的退出码,由 [`poll()`](#subprocess.Popen.poll "subprocess.Popen.poll") 和 [`wait()`](#subprocess.Popen.wait "subprocess.Popen.wait") 设置(以及直接由 [`communicate()`](#subprocess.Popen.communicate "subprocess.Popen.communicate") 设置)。一个 `None` 值 表示此进程仍未结束。 一个负值 `-N` 表示子进程被信号 `N` 中断 (仅 POSIX). ## Windows Popen 助手 [`STARTUPINFO`](#subprocess.STARTUPINFO "subprocess.STARTUPINFO") 类和以下常数仅在 Windows 有效。 *class* `subprocess.``STARTUPINFO`(*\**, *dwFlags=0*, *hStdInput=None*, *hStdOutput=None*, *hStdError=None*, *wShowWindow=0*, *lpAttributeList=None*)在 [`Popen`](#subprocess.Popen "subprocess.Popen") 创建时部分支持 Windows 的 [STARTUPINFO](https://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx) \[https://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx\] 结构。接下来的属性仅能通过关键词参数设置。 在 3.7 版更改: 仅关键词参数支持被加入。 `dwFlags`A bit field that determines whether certain [`STARTUPINFO`](#subprocess.STARTUPINFO "subprocess.STARTUPINFO")attributes are used when the process creates a window. ``` si = subprocess.STARTUPINFO() si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW ``` `hStdInput`If [`dwFlags`](#subprocess.STARTUPINFO.dwFlags "subprocess.STARTUPINFO.dwFlags") specifies [`STARTF_USESTDHANDLES`](#subprocess.STARTF_USESTDHANDLES "subprocess.STARTF_USESTDHANDLES"), this attribute is the standard input handle for the process. If [`STARTF_USESTDHANDLES`](#subprocess.STARTF_USESTDHANDLES "subprocess.STARTF_USESTDHANDLES") is not specified, the default for standard input is the keyboard buffer. `hStdOutput`If [`dwFlags`](#subprocess.STARTUPINFO.dwFlags "subprocess.STARTUPINFO.dwFlags") specifies [`STARTF_USESTDHANDLES`](#subprocess.STARTF_USESTDHANDLES "subprocess.STARTF_USESTDHANDLES"), this attribute is the standard output handle for the process. Otherwise, this attribute is ignored and the default for standard output is the console window's buffer. `hStdError`If [`dwFlags`](#subprocess.STARTUPINFO.dwFlags "subprocess.STARTUPINFO.dwFlags") specifies [`STARTF_USESTDHANDLES`](#subprocess.STARTF_USESTDHANDLES "subprocess.STARTF_USESTDHANDLES"), this attribute is the standard error handle for the process. Otherwise, this attribute is ignored and the default for standard error is the console window's buffer. `wShowWindow`If [`dwFlags`](#subprocess.STARTUPINFO.dwFlags "subprocess.STARTUPINFO.dwFlags") specifies [`STARTF_USESHOWWINDOW`](#subprocess.STARTF_USESHOWWINDOW "subprocess.STARTF_USESHOWWINDOW"), this attribute can be any of the values that can be specified in the `nCmdShow`parameter for the [ShowWindow](https://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx) \[https://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx\]function, except for `SW_SHOWDEFAULT`. Otherwise, this attribute is ignored. [`SW_HIDE`](#subprocess.SW_HIDE "subprocess.SW_HIDE") is provided for this attribute. It is used when [`Popen`](#subprocess.Popen "subprocess.Popen") is called with `shell=True`. `lpAttributeList`A dictionary of additional attributes for process creation as given in `STARTUPINFOEX`, see [UpdateProcThreadAttribute](https://msdn.microsoft.com/en-us/library/windows/desktop/ms686880(v=vs.85).aspx) \[https://msdn.microsoft.com/en-us/library/windows/desktop/ms686880(v=vs.85).aspx\]. Supported attributes: **handle\_list**Sequence of handles that will be inherited. *close\_fds* must be true if non-empty. The handles must be temporarily made inheritable by [`os.set_handle_inheritable()`](os.xhtml#os.set_handle_inheritable "os.set_handle_inheritable") when passed to the [`Popen`](#subprocess.Popen "subprocess.Popen")constructor, else [`OSError`](exceptions.xhtml#OSError "OSError") will be raised with Windows error `ERROR_INVALID_PARAMETER` (87). 警告 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.xhtml#os.system "os.system"). This also applies to standard handle redirection, which temporarily creates inheritable handles. 3\.7 新版功能. ### Windows Constants The [`subprocess`](#module-subprocess "subprocess: Subprocess management.") module exposes the following constants. `subprocess.``STD_INPUT_HANDLE`The standard input device. Initially, this is the console input buffer, `CONIN$`. `subprocess.``STD_OUTPUT_HANDLE`The standard output device. Initially, this is the active console screen buffer, `CONOUT$`. `subprocess.``STD_ERROR_HANDLE`The standard error device. Initially, this is the active console screen buffer, `CONOUT$`. `subprocess.``SW_HIDE`Hides the window. Another window will be activated. `subprocess.``STARTF_USESTDHANDLES`Specifies that the [`STARTUPINFO.hStdInput`](#subprocess.STARTUPINFO.hStdInput "subprocess.STARTUPINFO.hStdInput"), [`STARTUPINFO.hStdOutput`](#subprocess.STARTUPINFO.hStdOutput "subprocess.STARTUPINFO.hStdOutput"), and [`STARTUPINFO.hStdError`](#subprocess.STARTUPINFO.hStdError "subprocess.STARTUPINFO.hStdError") attributes contain additional information. `subprocess.``STARTF_USESHOWWINDOW`Specifies that the [`STARTUPINFO.wShowWindow`](#subprocess.STARTUPINFO.wShowWindow "subprocess.STARTUPINFO.wShowWindow") attribute contains additional information. `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`](#subprocess.Popen "subprocess.Popen")`creationflags` parameter to specify that a new process group will be created. This flag is necessary for using [`os.kill()`](os.xhtml#os.kill "os.kill")on the subprocess. This flag is ignored if [`CREATE_NEW_CONSOLE`](#subprocess.CREATE_NEW_CONSOLE "subprocess.CREATE_NEW_CONSOLE") is specified. `subprocess.``ABOVE_NORMAL_PRIORITY_CLASS`A [`Popen`](#subprocess.Popen "subprocess.Popen")`creationflags` parameter to specify that a new process will have an above average priority. 3\.7 新版功能. `subprocess.``BELOW_NORMAL_PRIORITY_CLASS`A [`Popen`](#subprocess.Popen "subprocess.Popen")`creationflags` parameter to specify that a new process will have a below average priority. 3\.7 新版功能. `subprocess.``HIGH_PRIORITY_CLASS`A [`Popen`](#subprocess.Popen "subprocess.Popen")`creationflags` parameter to specify that a new process will have a high priority. 3\.7 新版功能. `subprocess.``IDLE_PRIORITY_CLASS`A [`Popen`](#subprocess.Popen "subprocess.Popen")`creationflags` parameter to specify that a new process will have an idle (lowest) priority. 3\.7 新版功能. `subprocess.``NORMAL_PRIORITY_CLASS`A [`Popen`](#subprocess.Popen "subprocess.Popen")`creationflags` parameter to specify that a new process will have an normal priority. (default) 3\.7 新版功能. `subprocess.``REALTIME_PRIORITY_CLASS`A [`Popen`](#subprocess.Popen "subprocess.Popen")`creationflags` parameter to specify that a new process will have realtime priority. You should almost never use REALTIME\_PRIORITY\_CLASS, because this interrupts system threads that manage mouse input, keyboard input, and background disk flushing. This class can be appropriate for applications that "talk" directly to hardware or that perform brief tasks that should have limited interruptions. 3\.7 新版功能. `subprocess.``CREATE_NO_WINDOW`A [`Popen`](#subprocess.Popen "subprocess.Popen")`creationflags` parameter to specify that a new process will not create a window. 3\.7 新版功能. `subprocess.``DETACHED_PROCESS`A [`Popen`](#subprocess.Popen "subprocess.Popen")`creationflags` parameter to specify that a new process will not inherit its parent's console. This value cannot be used with CREATE\_NEW\_CONSOLE. 3\.7 新版功能. `subprocess.``CREATE_DEFAULT_ERROR_MODE`A [`Popen`](#subprocess.Popen "subprocess.Popen")`creationflags` parameter to specify that a new process does not inherit the error mode of the calling process. Instead, the new process gets the default error mode. This feature is particularly useful for multithreaded shell applications that run with hard errors disabled. 3\.7 新版功能. `subprocess.``CREATE_BREAKAWAY_FROM_JOB`A [`Popen`](#subprocess.Popen "subprocess.Popen")`creationflags` parameter to specify that a new process is not associated with the job. 3\.7 新版功能. ## Older high-level API Prior to Python 3.5, these three functions comprised the high level API to subprocess. You can now use [`run()`](#subprocess.run "subprocess.run") in many cases, but lots of existing code calls these functions. `subprocess.``call`(*args*, *\**, *stdin=None*, *stdout=None*, *stderr=None*, *shell=False*, *cwd=None*, *timeout=None*)Run the command described by *args*. Wait for command to complete, then return the [`returncode`](#subprocess.Popen.returncode "subprocess.Popen.returncode") attribute. Code needing to capture stdout or stderr should use [`run()`](#subprocess.run "subprocess.run") instead: > run(...).returncode To suppress stdout or stderr, supply a value of [`DEVNULL`](#subprocess.DEVNULL "subprocess.DEVNULL"). The arguments shown above are merely some common ones. The full function signature is the same as that of the [`Popen`](#subprocess.Popen "subprocess.Popen") constructor - this function passes all supplied arguments other than *timeout* directly through to that interface. 注解 Do not use `stdout=PIPE` or `stderr=PIPE` with this function. 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. 在 3.3 版更改: *timeout* 被添加 `subprocess.``check_call`(*args*, *\**, *stdin=None*, *stdout=None*, *stderr=None*, *shell=False*, *cwd=None*, *timeout=None*)Run command with arguments. Wait for command to complete. If the return code was zero then return, otherwise raise [`CalledProcessError`](#subprocess.CalledProcessError "subprocess.CalledProcessError"). The [`CalledProcessError`](#subprocess.CalledProcessError "subprocess.CalledProcessError") object will have the return code in the [`returncode`](#subprocess.CalledProcessError.returncode "subprocess.CalledProcessError.returncode") attribute. Code needing to capture stdout or stderr should use [`run()`](#subprocess.run "subprocess.run") instead: > run(..., check=True) To suppress stdout or stderr, supply a value of [`DEVNULL`](#subprocess.DEVNULL "subprocess.DEVNULL"). The arguments shown above are merely some common ones. The full function signature is the same as that of the [`Popen`](#subprocess.Popen "subprocess.Popen") constructor - this function passes all supplied arguments other than *timeout* directly through to that interface. 注解 Do not use `stdout=PIPE` or `stderr=PIPE` with this function. 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. 在 3.3 版更改: *timeout* 被添加 `subprocess.``check_output`(*args*, *\**, *stdin=None*, *stderr=None*, *shell=False*, *cwd=None*, *encoding=None*, *errors=None*, *universal\_newlines=None*, *timeout=None*, *text=None*)Run command with arguments and return its output. If the return code was non-zero it raises a [`CalledProcessError`](#subprocess.CalledProcessError "subprocess.CalledProcessError"). The [`CalledProcessError`](#subprocess.CalledProcessError "subprocess.CalledProcessError") object will have the return code in the [`returncode`](#subprocess.CalledProcessError.returncode "subprocess.CalledProcessError.returncode") attribute and any output in the [`output`](#subprocess.CalledProcessError.output "subprocess.CalledProcessError.output") attribute. 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()`](#subprocess.run "subprocess.run") - most arguments are passed directly through to that interface. However, explicitly passing `input=None` to inherit the parent's standard input file handle is not supported. 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()`](#subprocess.run "subprocess.run"). To also capture standard error in the result, use `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' ``` 3\.1 新版功能. 在 3.3 版更改: *timeout* 被添加 在 3.4 版更改: Support for the *input* keyword argument was added. 在 3.6 版更改: *encoding* and *errors* were added. See [`run()`](#subprocess.run "subprocess.run") for details. 3\.7 新版功能: *text* 作为 *universal\_newlines* 的一个更具可读性的别名被添加。 ## Replacing Older Functions with the [`subprocess`](#module-subprocess "subprocess: Subprocess management.") Module In this section, "a becomes b" means that b can be used as a replacement for a. 注解 All "a" functions in this section fail (more or less) silently if the executed program cannot be found; the "b" replacements raise [`OSError`](exceptions.xhtml#OSError "OSError")instead. In addition, the replacements using [`check_output()`](#subprocess.check_output "subprocess.check_output") will fail with a [`CalledProcessError`](#subprocess.CalledProcessError "subprocess.CalledProcessError") if the requested operation produces a non-zero return code. The output is still available as the [`output`](#subprocess.CalledProcessError.output "subprocess.CalledProcessError.output") attribute of the raised exception. In the following examples, we assume that the relevant functions have already been imported from the [`subprocess`](#module-subprocess "subprocess: Subprocess management.") module. ### Replacing /bin/sh shell backquote ``` 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. Alternatively, for trusted input, the shell's own pipeline support may still be used directly: ``` output=`dmesg | grep hda` ``` becomes: ``` output=check_output("dmesg | grep hda", shell=True) ``` ### Replacing [`os.system()`](os.xhtml#os.system "os.system") ``` sts = os.system("mycmd" + " myarg") # becomes sts = call("mycmd" + " myarg", shell=True) ``` 注释: - Calling the program through the shell is usually not required. 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`](os.xhtml#os.spawnl "os.spawnl") family 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.xhtml#os.popen "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 注解 If the cmd argument to popen2 functions is a string, the command is executed through /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`](#subprocess.Popen "subprocess.Popen"), except that: - [`Popen`](#subprocess.Popen "subprocess.Popen") raises an exception if the execution fails. - The *capturestderr* argument is replaced with the *stderr* argument. - `stdin=PIPE` and `stdout=PIPE` must be specified. - popen2 closes all file descriptors by default, but you have to specify `close_fds=True` with [`Popen`](#subprocess.Popen "subprocess.Popen") to guarantee this behavior on all platforms or past Python versions. ## Legacy Shell Invocation Functions This module also provides the following legacy functions from the 2.x `commands` module. 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. Execute the string *cmd* in a shell with `Popen.check_output()` and return a 2-tuple `(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](intro.xhtml#availability): POSIX & Windows. 在 3.3.4 版更改: Windows support was added. The function now returns (exitcode, output) instead of (status, output) as it did in Python 3.3.3 and earlier. exitcode has the same value as [`returncode`](#subprocess.Popen.returncode "subprocess.Popen.returncode"). `subprocess.``getoutput`(*cmd*)Return output (stdout and stderr) of executing *cmd* in a shell. Like [`getstatusoutput()`](#subprocess.getstatusoutput "subprocess.getstatusoutput"), except the exit code is ignored and the return value is a string containing the command's output. Example: ``` >>> subprocess.getoutput('ls /bin/ls') '/bin/ls' ``` [Availability](intro.xhtml#availability): POSIX & Windows. 在 3.3.4 版更改: Windows support added ## 注释 ### Converting an argument sequence to a string on 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): 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. 参见 [`shlex`](shlex.xhtml#module-shlex "shlex: Simple lexical analysis for Unix shell-like languages.")Module which provides function to parse and escape command lines. ### 导航 - [索引](../genindex.xhtml "总目录") - [模块](../py-modindex.xhtml "Python 模块索引") | - [下一页](sched.xhtml "sched --- 事件调度器") | - [上一页](concurrent.futures.xhtml "concurrent.futures --- 启动并行任务") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) » - zh\_CN 3.7.3 [文档](../index.xhtml) » - [Python 标准库](index.xhtml) » - [并发执行](concurrency.xhtml) » - $('.inline-search').show(0); | © [版权所有](../copyright.xhtml) 2001-2019, Python Software Foundation. Python 软件基金会是一个非盈利组织。 [请捐助。](https://www.python.org/psf/donations/) 最后更新于 5月 21, 2019. [发现了问题](../bugs.xhtml)? 使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 创建。