简体   繁体   English

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

[英]How to read the “error” content generated in the command line using Python?

Test is on Linux 32bit. 测试是在Linux 32位上进行的。 Python 2.7 Python 2.7

I want to run this command in Python 我想在Python中运行此命令

 nasm -f elf target.s

and collect the assembly error message this command generates such as these: 并收集此命令生成的组装错误消息,例如:

target.s:422: error: symbol `loc_8049B1C' undefined
target.s:423: error: symbol `loc_80499E8' undefined
target.s:424: error: symbol `loc_80499AE' undefined

I firstly use this: 我首先使用这个:

infos = subprocess.check_output(["nasm", "-f", "elf", "final.s"], stderr=subprocess.STDOUT)

Python tells me that Python告诉我

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

and program terminated 并且程序终止

Then I use this: 然后我用这个:

 infos = os.popen("nasm -f elf target.s").read()

Then infos gets nothing. 然后信息一无所获。

So basically could anyone tell me how to get the error message info while keeping the Python program running as normal? 所以基本上任何人都可以告诉我如何在保持Python程序正常运行的同时获取错误消息信息吗?

Thank you! 谢谢!

I would use the .communicate() to get the standard error if any. 我将使用.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

Check output raises a CalledProcessError when the process has a non-zero return status. 当进程的返回状态为非零时,检查输出将引发CalledProcessError。

The output should be in the output attribute of the exception object. 输出应位于异常对象的输出属性中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM