为什么在Python中没有报告来自多处理的错误,以及如何打开报告错误? [英] Why no errors from multiprocessing is reported in Python and how to switch on reporting errors?

查看:12
本文介绍了为什么在Python中没有报告来自多处理的错误,以及如何打开报告错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

# 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 

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

这篇关于为什么在Python中没有报告来自多处理的错误,以及如何打开报告错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆