Python: Getting a traceback from a multiprocessing.Process

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

    Python 3

    In Python 3, now the get method of multiprocessing.pool.Async returns full traceback, see http://bugs.python.org/issue13831.

    Python 2

    Use the traceback.format_exc (which means formatted expetion) to get the traceback string. It would be much more covenient with making a decorator as below.

    def full_traceback(func):
        import traceback, functools
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except Exception as e:
                msg = "{}\n\nOriginal {}".format(e, traceback.format_exc())
                raise type(e)(msg)
        return wrapper
    

    Example:

    def func0():
        raise NameError("func0 exception")
    
    def func1():
        return func0()
    
    # Key is here!
    @full_traceback
    def main(i):
        return func1()
    
    if __name__ == '__main__':
        from multiprocessing import Pool
        pool = Pool(4)
        try:
            results = pool.map_async(main, range(5)).get(1e5)
        finally:
            pool.close()
            pool.join()
    

    The traceback with the decorator:

    Traceback (most recent call last):
      File "bt.py", line 34, in <module>
        results = pool.map_async(main, range(5)).get(1e5)
      File "/opt/anaconda/lib/python2.7/multiprocessing/pool.py", line 567, in get
        raise self._value
    NameError: Exception in func0
    
    Original Traceback (most recent call last):
      File "bt.py", line 13, in wrapper
        return func(*args, **kwargs)
      File "bt.py", line 27, in main
        return func1()
      File "bt.py", line 23, in func1
        return func0()
      File "bt.py", line 20, in func0
        raise NameError("Exception in func0")
    NameError: Exception in func0
    

    The traceback without the decorator:

    Traceback (most recent call last):
      File "bt.py", line 34, in <module>
        results = pool.map_async(main, range(5)).get(1e5)
      File "/opt/anaconda/lib/python2.7/multiprocessing/pool.py", line 567, in get
        raise self._value
    NameError: Exception in func0
    
    0 讨论(0)
提交回复
热议问题