Python 子流程:意外的关键字参数捕获\u输出

Python 子流程:意外的关键字参数捕获\u输出,python,subprocess,python-3.6,python-3.7,Python,Subprocess,Python 3.6,Python 3.7,执行中给出的subprocess.run()时,我得到一个类型错误: >>> 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/python

执行中给出的
subprocess.run()
时,我得到一个类型错误:

>>> 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'

您检查了错误的文档,因为此参数不存在,如中所示(选择左上角的版本):

但是,通过将
stdout
stderr
设置为
PIPE
,您可以轻松地“模拟”这一点:

from subprocess import PIPE

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

我遇到这个错误是因为我调用了(这是旧的高级API)而不是。

最简单的方法是使用函数:

import subprocess
subprocess.check_output(["ls", "-l", "/dev/null"])

capture\u output
在Python3.7中是新的。如果我尝试使用这里提供的解决方案,我会得到“name'PIPE'未定义”。@ScottF:您确实从subprocess import PIPE导入了它
(如代码片段顶部所示)?
from subprocess import PIPE

subprocess.run(["ls", "-l", "/dev/null"], stdout=PIPE, stderr=PIPE)
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
import subprocess
subprocess.check_output(["ls", "-l", "/dev/null"])