The documentation说:
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_sub_program.py的内容:
raise Exception("I am raised!")
my_main_program.py的内容:
import sysimport subprocesstry: 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_tracebackAttributeError: 'CalledProcessError' object has no attribute 'child_traceback'
如何在不修改子进程程序代码的情况下访问子进程的回溯?这意味着,我想避免在我的整个子程序代码中添加一个大的try / except子句,而是处理来自我的主程序的错误记录.
编辑:sys.executable应该可以替换为与运行主程序的解释器不同的解释器.
解决方法 当您开始另一个Python进程时,您也可以尝试使用多处理python模块;通过对Process类进行子类化,可以很容易地从目标函数中获取异常:from multiprocessing import Process,Pipeimport tracebackimport functoolsclass MyProcess(Process): def __init__(self,*args,**kwargs): Process.__init__(self,**kwargs) self._pconn,self._cconn = Pipe() self._exception = None def run(self): try: Process.run(self) self._cconn.send(None) except Exception as e: tb = traceback.format_exc() self._cconn.send((e,tb)) # raise e # You can still rise this exception if you need to @property def exception(self): if self._pconn.poll(): self._exception = self._pconn.recv() return self._exceptionp = MyProcess(target=functools.partial(execfile,"my_sub_program.py"))p.start()p.join() #wait for sub-process to endif p.exception: error,traceback = p.exception print 'you got',traceback
诀窍是让目标函数执行Python子程序,这是通过使用functools.partial完成的.
总结以上是内存溢出为你收集整理的python – 子进程子跟踪全部内容,希望文章能够帮你解决python – 子进程子跟踪所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)