如何阅读;“错误”;使用Python在命令行中生成的内容?

如何阅读;“错误”;使用Python在命令行中生成的内容?,python,linux,Python,Linux,测试是在32位Linux上进行的。Python 2.7 我想在Python中运行这个命令 nasm -f elf target.s 并收集此命令生成的程序集错误消息,例如: target.s:422: error: symbol `loc_8049B1C' undefined target.s:423: error: symbol `loc_80499E8' undefined target.s:424: error: symbol `loc_80499AE' undefined 我首先用

测试是在32位Linux上进行的。Python 2.7

我想在Python中运行这个命令

 nasm -f elf target.s
并收集此命令生成的程序集错误消息,例如:

target.s:422: error: symbol `loc_8049B1C' undefined
target.s:423: error: symbol `loc_80499E8' undefined
target.s:424: error: symbol `loc_80499AE' undefined
我首先用这个:

infos = subprocess.check_output(["nasm", "-f", "elf", "final.s"], stderr=subprocess.STDOUT)
 infos = os.popen("nasm -f elf target.s").read()
Python告诉我

subprocess.CalledProcessError: Command '['nasm', '-f', 'elf', 'target.s']' returned non-zero exit status 1
和程序终止

然后我用这个:

infos = subprocess.check_output(["nasm", "-f", "elf", "final.s"], stderr=subprocess.STDOUT)
 infos = os.popen("nasm -f elf target.s").read()
那么infos什么也得不到

那么基本上谁能告诉我如何在保持Python程序正常运行的同时获取错误消息信息呢


谢谢大家!

当进程的返回状态为非零时,Check output会引发CalledProcessError

输出应该在异常对象的输出属性中

try:
  infos = subprocess.check_output(["nasm", "-f", "elf", "final.s"], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
  print e.output

我将使用.communicate()获取标准错误(如果有)

s = 'nasm -f elf target.s'
proc = subprocess.Popen(s.split(), stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE)
(stdout, stderr) = proc.communicate()
if stderr:
    print stderr

在我发布另一个答案之前,我几乎是一字不差地发布这个答案。我的假设是,使用“检查输出”是有特定原因的。