加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 子进程子跟踪

发布时间:2020-12-20 13:13:20 所属栏目:Python 来源:网络整理
导读:我想访问在子进程中运行的 python程序的回溯. 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 at
我想访问在子进程中运行的 python程序的回溯.

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 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应该可以替换为与运行主程序的解释器不同的解释器.

解决方法

当您开始另一个Python进程时,您也可以尝试使用多处理Python模块;通过对Process类进行子类化,可以很容易地从目标函数中获取异常:

from multiprocessing import Process,Pipe
import traceback
import functools

class 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._exception


p = MyProcess(target=functools.partial(execfile,"my_sub_program.py"))
p.start()
p.join() #wait for sub-process to end

if p.exception:
    error,traceback = p.exception
    print 'you got',traceback

诀窍是让目标函数执行Python子程序,这是通过使用functools.partial完成的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读