您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python:从multiprocessing.Process获取回溯

Python:从multiprocessing.Process获取回溯

使用tblib您可以传递包装的异常并在以后重新引发它们:

import tblib.pickling_support
tblib.pickling_support.install()

from multiprocessing import Pool
import sys


class ExceptionWrapper(object):

    def __init__(self, ee):
        self.ee = ee
        __, __, self.tb = sys.exc_info()

    def re_raise(self):
        raise self.ee.with_traceback(self.tb)
        # for Python 2 replace the prevIoUs line by:
        # raise self.ee, None, self.tb


# example of how to use ExceptionWrapper

def inverse(i):
    """ will fail for i == 0 """
    try:
        return 1.0 / i
    except Exception as e:
        return ExceptionWrapper(e)


def main():
    p = Pool(1)
    results = p.map(inverse, [0, 1, 2, 3])
    for result in results:
        if isinstance(result, ExceptionWrapper):
            result.re_raise()


if __name__ == "__main__":
    main()

因此,如果您在远程进程中捕获到异常,则将其包装ExceptionWrapper,然后将其传递回去。调用re_raise()主流程即可完成工作。

python 2022/1/1 18:27:19 有557人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶