我正在尝试使用"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)