我设置了一些简单的代码来测试多处理的一些问题处理,我无法跟踪此代码中的错误,因为没有来自进程的反馈。我怎么能从子进程中收到异常,因为现在我对它无视了。如何调试此代码。
# coding=utf-8
import multiprocessing
import multiprocessing.managers
import logging
def callback(result):
print multiprocessing.current_process().name, 'callback', result
def worker(io_lock, value):
# error
raise RuntimeError()
result = value + 1
with io_lock:
print multiprocessing.current_process().name, value, result
return result
def main():
manager = multiprocessing.Manager()
io_lock = manager.Lock()
pool = multiprocessing.Pool(multiprocessing.cpu_count())
for i in range(10):
print pool.apply_async(worker, args=(io_lock, i), callback = callback)
pool.close()
pool.join()
if __name__ == '__main__':
logging.basicConfig(level = logging.DEBUG)
main()
答案 0 :(得分:2)
您可以尝试,捕获和记录工作进程内发生的异常。像这样的东西
def worker(io_lock, value):
try:
raise RuntimeError('URGH') # Or do your actual work here
except:
logging.exception('Exception occurred: ')
raise # Re-raise the exception so that the process exits
异常日志处理程序将自动包含堆栈跟踪。