子进程:意外的关键字参数 capture_output [英] subprocess: unexpected keyword argument capture_output
问题描述
当执行 subprocess.run()
时,如 Python 文档,我得到一个类型错误:
我正在运行 Python 3.6.6:
$ python3 --version蟒蛇 3.6.6
您检查了错误的文档,对于 python-3.6 这个参数不存在,可以在 文档(您选择左上角的版本):
<块引用>subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None,shell=False, cwd=None, timeout=None, check=False, encoding=None,错误=无,环境=无)
然而,您可以轻松地模仿"这是通过将 stdout
和 stderr
设置为 PIPE
来实现的:
from subprocess import PIPEsubprocess.run(["ls", "-l", "/dev/null"], stdout=PIPE, stderr=PIPE)
预>其实如果我们看一下python-3.7 版本,该功能被引入的地方,我们在 源代码 [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 python-3.6 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
andstderr
toPIPE
: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 python-3.7 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屋!