【发布时间】:2020-09-05 20:24:37
【问题描述】:
如何从使用multiprocessing.Process() 执行的进程中捕获异常?
考虑以下使用mulitprocessing.Process()在子进程内部执行简单failFunction()(立即引发运行时错误)的python脚本
#!/usr/bin/env python3
import multiprocessing, time
# this function will be executed in a child process asynchronously
def failFunction():
raise RuntimeError('trust fall, catch me!')
# execute the helloWorld() function in a child process in the background
process = multiprocessing.Process(
target = failFunction,
)
process.start()
# <this is where async stuff would happen>
time.sleep(1)
# try (and fail) to catch the exception
try:
process.join()
except Exception as e:
print( "This won't catch the exception" )
从以下执行中可以看出,尝试包装 .join() 确实不实际上捕获了异常
user@host:~$ python3 example.py
Process Process-1:
Traceback (most recent call last):
File "/usr/lib/python3.7/multiprocessing/process.py", line 297, in _bootstrap
self.run()
File "/usr/lib/python3.7/multiprocessing/process.py", line 99, in run
self._target(*self._args, **self._kwargs)
File "example4.py", line 6, in failFunction
raise RuntimeError('trust fall, catch me!')
RuntimeError: trust fall, catch me!
user@host:~$
如何更新上述脚本以实际捕获使用multiprocessing.Process() 在子进程内部执行的函数的异常?
【问题讨论】:
-
我相信在这种情况下你必须自己传达进程,因为一旦你执行
fork,子进程就会独立存在 - 我不相信这样的“异常传播”在操作系统级别上是可能的。这是一个非常合理的使用队列的方法:stackoverflow.com/a/19929767/5430833
标签: python python-3.x exception multiprocessing