Python: Getting a traceback from a multiprocessing.Process

前端 未结 7 1400
后悔当初
后悔当初 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:14

    This is a variation of this excellent answer. Both are relying on tblib for storing the traceback.

    However, instead of having to return the exception object (as asked for by the OP), the worker function can be left as-is and is just wrapped in try/except to store exceptions for re-raise.

    import tblib.pickling_support
    tblib.pickling_support.install()
    
    import sys
    
    class DelayedException(Exception):
    
        def __init__(self, ee):
            self.ee = ee
            __,  __, self.tb = sys.exc_info()
            super(DelayedException, self).__init__(str(ee))
    
        def re_raise(self):
            raise self.ee, None, self.tb
    

    Example

    def worker():
        try:
            raise ValueError('Something went wrong.')
        except Exception as e:
            raise DelayedException(e)
    
    
    if __name__ == '__main__':
    
        import multiprocessing
    
        pool = multiprocessing.Pool()
        try:
            pool.imap(worker, [1, 2, 3])
        except DelayedException as e:
            e.re_raise()
    

提交回复
热议问题