check_output在 Python 3.6 中不起作用,而子进程工作正常



我正在尝试使用"check_output"方法在我的 Python 程序中获取命令的输出。 但是我收到此错误:

out = check_output(command5 , shell=True)

文件 "/usr/lib64/python3.6/subprocess.py",第 336 行,check_output **kwargs(.stdout 文件 "/usr/lib64/python3.6/subprocess.py",第 418 行,正在运行 output=stdout, stderr=stderr( 子流程。CalledProcessError: 命令 'oscap xccdf eval --profile xccdf_org.ssgproject.content_profile_rht-ccp --results-arf arf.xml/usr/share/xml/scap/ssg/content/ssg-centos7-ds.xml' 返回非零退出状态 2。

这是我的程序的相关部分:

command4 = "oscap xccdf eval --profile xccdf_org.ssgproject.content_profile_rht-ccp --results-arf arf.xml /usr/share/xml/scap/ssg/content/ssg-centos7-ds.xml"
out = check_output(command4 , shell=True)

我确定该命令没问题,因为我在编写时得到结果:

subprocess.call(command5,shell=True)

我正在使用python 3.6,并在centos 7中工作。

知道为什么check_output不能得到结果吗?

这是完全正常的,因为您运行的命令生成了非零退出代码。这意味着您运行的命令发出信号,表明可能有问题。

请参阅subprocess.check_output()文档:

如果返回代码不为零,则会引发 CalledProcessError。

这相当于:

run(..., check=True, stdout=PIPE).stdout

check=True标志告诉run()在未0时引发异常return_value

如果 check 为 true,并且进程以非零退出代码退出,则会引发CalledProcessError异常。

您使用的另一个函数subprocess.call()没有设置check=True

运行args描述的命令。等待命令完成,然后返回returncode属性。

这相当于:

run(...).returncode

所以要么不要使用check_output(),要么捕获引发的异常,要么修复您正在运行的命令。call()奏效并不表明这一进程实际上产生了成功的结果。

例如,您可以直接使用subprocess.run()

proc = subprocess.run(
command5, shell=True, text=True
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if proc.returncode:
print(f'Issue reported, exit code {proc.returncode}, stderr:')
print(proc.stderr)
else:
print(proc.stdout)

相关内容

最新更新