为什么 Python 中没有报告来自多处理的错误以及如何打开报告错误?

Why no errors from multiprocessing is reported in Python and how to switch on reporting errors?

我设置了一些简单的代码来测试多处理的一些问题处理,我无法跟踪此代码中的错误,因为没有来自进程的反馈。我怎么能从子流程中收到异常,因为现在我对此视而不见。如何调试此代码。

# 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()

您可以尝试、捕获和记录工作进程内发生的异常。像这样

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 

异常日志处理程序将自动包含堆栈跟踪。