多进程中的很多报错并不会打印到终端,这给我们调试代码带来很大麻烦。
现在用这个方法就可以把报错打印出来,也是我实习过程中偷师出来,给自己也记录一下。
def error(msg, *args):
return multiprocessing.get_logger().error(msg, *args)
class LogExceptions(object):
def __init__(self, callable):
self.__callable = callable
return
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
pass
随后在自己调用多进程执行函数时,把这个LogExceptions函数套在我们需要执行的函数上,如下,套在data_write上:
for i in range(cnt):
multi_rows = rows[i*step:(i+1)*step]
# data_write(multi_rows,model,preprocess,device)
pool.apply_async(LogExceptions(data_write),(multi_rows,model,preprocess,device,))