python-3.x - 如何捕获进程目标中发生的异常?
问题描述
我正在创建一个执行功能的流程。如果函数引发异常,我将无法捕获它。以下是示例代码。
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
解决方案
推荐阅读
- azure-devops - Azure DevOps 每次提交都会增加 VersionPrefix
- sql-server-2014 - SQL Server:如何获取将 2 个表与不应比较的另一列进行比较的额外记录
- angular - 使用 ngTemplate 使用 Angular 显示元素 html
- node.js - 在猫鼬中递归查找
- applescript - 在 AppleScript 中过滤记录
- javascript - Photoshop CC Javascript - 删除/剪切选区
- javascript - 在 onbeforeunload 事件期间执行调用
- php - 无法将 PHP7 安装到 AWS EC2 实例?
- python - 如何将参数传递给夹具并在测试方法中使用此夹具?
- ruby-on-rails-4 - 升级到 Rails 5.2 后 nil:NilClass 的未定义方法“expr”