我想访问在子进程中运行的python程序的回溯。子进程子追踪
The documentation说:的my_sub_program.py
Exceptions raised in the child process, before the new program has started to execute, will be re-raised in the parent. Additionally, the exception object will have one extra attribute called child_traceback, which is a string containing traceback information from the child’s point of view.
内容:的my_main_program.py
raise Exception("I am raised!")
内容:
import sys
import subprocess
try:
subprocess.check_output([sys.executable, "my_sub_program.py"])
except Exception as e:
print e.child_traceback
如果我跑my_main_program.py
,我得到以下错误:
Traceback (most recent call last):
File "my_main_program.py", line 6, in <module>
print e.child_traceback
AttributeError: 'CalledProcessError' object has no attribute 'child_traceback'
如何在不修改子进程程序代码的情况下访问子进程的回溯?这意味着,我想避免在我的整个子程序代码中添加一个大的try/except
子句,而是处理来自主程序的错误日志记录。
编辑:sys.executable
应该可以用与运行主程序的解释器不同的解释器替换。
Doc说“在新程序开始执行之前”,在你的情况下,新程序执行时引发了异常,因此没有'child_traceback'。一旦新程序运行,您需要捕获'CalledProcessError'异常,并执行以下操作:http://stackoverflow.com/questions/24849998/how-to-catch-exception-output-from-python-subprocess-check使用'CalledProcessError.output'输出 – mguijarr
在我的示例中,'CalledProcessError.output'只捕获标准输出,但不捕获异常的回溯。 – schreon
这可能是因为输出是在'stderr'上发送的。看看我给你的问题上面的链接的答案更多详细信息 – mguijarr