我对这个问题的合理解决,至少在调试的目的。目前我还没有一个解决方案可以在主流程中引发异常。我的第一个想法是使用装饰,但你只能腌functions defined at the top level of a module,所以这是正确的。
取而代之的是一个简单的包装类和一个Pool子类,它使用apply_async
(因此为apply
)。我将离开map_async
作为读者的练习。
import traceback
from multiprocessing.pool import Pool
import multiprocessing
# Shortcut to multiprocessing's logger
def error(msg, *args):
return multiprocessing.get_logger().error(msg, *args)
class LogExceptions(object):
def __init__(self, callable):
self.__callable = callable
def __call__(self, *args, **kwargs):
try:
result = self.__callable(*args, **kwargs)
except Exception as e:
# Here we add some debugging help. If multiprocessing's
# debugging is on, it will arrange to log the traceback
error(traceback.format_exc())
# Re-raise the original exception so the Pool worker can
# clean up
raise
# It was fine, give a normal answer
return result
class LoggingPool(Pool):
def apply_async(self, func, args=(), kwds={}, callback=None):
return Pool.apply_async(self, LogExceptions(func), args, kwds, callback)
def go():
print(1)
raise Exception()
print(2)
multiprocessing.log_to_stderr()
p = LoggingPool(processes=1)
p.apply_async(go)
p.close()
p.join()
这给了我:
1
[ERROR/PoolWorker-1] Traceback (most recent call last):
File "mpdebug.py", line 24, in __call__
result = self.__callable(*args, **kwargs)
File "mpdebug.py", line 44, in go
raise Exception()
Exception
我有同样的问题。原因如下:工作进程捕获异常并在结果队列中放置失败代码和异常。回到主进程中,Pool的结果处理线程获取失败代码并忽略它。某种猴子补丁调试模式可能是可能的。另一种方法是确保你的工作者函数捕获任何异常,返回它并为你的处理器打印一个错误代码。 –
这已经在这里回答:http://stackoverflow.com/a/26096355/512111 – j08lue