子进程:意外的关键字参数 capture_output [英] subprocess: unexpected keyword argument capture_output

查看:22
本文介绍了子进程:意外的关键字参数 capture_output的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当执行 subprocess.run() 时,如 Python 文档,我得到一个类型错误:

<预><代码>>>>导入子流程>>>subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中运行中的文件/usr/lib/python3.6/subprocess.py",第 403 行使用 Popen(*popenargs, **kwargs) 作为进程:类型错误:__init__() 得到了一个意外的关键字参数capture_output"

我正在运行 Python 3.6.6:

$ python3 --version蟒蛇 3.6.6

解决方案

您检查了错误的文档,对于 这个参数存在,可以在 文档(您选择左上角的版本):

<块引用>

subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None,shell=False, cwd=None, timeout=None, check=False, encoding=None,错误=无,环境=无)

然而,您可以轻松地模仿"这是通过将 stdoutstderr 设置为 PIPE 来实现的:

from subprocess import PIPEsubprocess.run(["ls", "-l", "/dev/null"], stdout=PIPE, stderr=PIPE)

其实如果我们看一下 版本,该功能被引入的地方,我们在 源代码 [GitHub]:

<块引用>

if capture_output:如果(kwargs 中的'stdout')或(kwargs 中的'stderr'):raise ValueError('stdout 和 stderr 参数不能被使用 ''带有捕获输出.')kwargs['stdout'] = PIPEkwargs['stderr'] = PIPE

When executing subprocess.run() as given in the Python docs, I get a TypeError:

>>> import subprocess
>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/subprocess.py", line 403, in run
    with Popen(*popenargs, **kwargs) as process:
TypeError: __init__() got an unexpected keyword argument 'capture_output'

I am running Python 3.6.6:

$ python3 --version
Python 3.6.6

解决方案

You inspected the wrong documentation, for this parameter does not exist, as can be found in the documentation (you select the version at the top left):

subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None,
               shell=False, cwd=None, timeout=None, check=False, encoding=None,
               errors=None, env=None)

You can however easily "emulate" this by setting both stdout and stderr to PIPE:

from subprocess import PIPE

subprocess.run(["ls", "-l", "/dev/null"], stdout=PIPE, stderr=PIPE)

In fact, if we look at the source code of the version, where the feature was introduced, we see in the source code [GitHub]:

if capture_output:
    if ('stdout' in kwargs) or ('stderr' in kwargs):
        raise ValueError('stdout and stderr arguments may not be used '
                         'with capture_output.')
    kwargs['stdout'] = PIPE
    kwargs['stderr'] = PIPE

这篇关于子进程:意外的关键字参数 capture_output的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆