首页 > 解决方案 > 如何捕获进程目标中发生的异常?

问题描述

我正在创建一个执行功能的流程。如果函数引发异常,我将无法捕获它。以下是示例代码。

from multiprocessing import Process
import traceback
import time


class CustomTimeoutException(Exception):
    pass

def temp1():
    time.sleep(5)
    print('In temp1')
    raise Exception('I have raised an exception')

def main():
    try:
        p = Process(target=temp1)
        p.start()
        p.join(10)
        if p.is_alive():
            p.terminate()
            raise CustomTimeoutException('Timeout')

    except CustomTimeoutException as e:
        print('in Custom')
        print(e)

    except Exception as e:
        print('In exception')
        print(e)


if __name__ == "__main__":
    main()

当我运行上面的代码时,在 temp1 中引发的异常不会被捕获。下面是示例输出

In temp1
Process Process-1:
Traceback (most recent call last):
  File "/usr/lib/python3.5/multiprocessing/process.py", line 249, in _bootstrap
    self.run()
  File "/usr/lib/python3.5/multiprocessing/process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "temp.py", line 12, in temp1
    raise Exception('I have raised an exception')
Exception: I have raised an exception

我还尝试过覆盖https://stackoverflow.com/a/33599967/9971556中提到的 Process 类的 run 方法不是很有帮助。

预期输出:

In exception
I have raised an exception

标签: python-3.xexceptionpython-multiprocessing

解决方案


推荐阅读