Python: Getting a traceback from a multiprocessing.Process

前端 未结 7 1406
后悔当初
后悔当初 2020-11-30 01:45

I am trying to get hold of a traceback object from a multiprocessing.Process. Unfortunately passing the exception info through a pipe does not work because traceback objects

7条回答
  •  暖寄归人
    2020-11-30 02:23

    Using tblib you can pass wrapped exceptions and reraise them later:

    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()
    

    So, if you catch an exception in your remote process, wrap it with ExceptionWrapper and then pass it back. Calling re_raise() in the main process will do the work.

提交回复
热议问题