在多处理池中使用时,不会正确引发自定义异常

时间:2015-01-16 22:07:55

标签: python exception python-3.x

问题

我正在观察Python 3.3.4中的行为,我想帮助理解:为什么在正常执行函数时正确引发异常,而不是在函数池中执行函数时?

代码

import multiprocessing

class AllModuleExceptions(Exception):
    """Base class for library exceptions"""
    pass

class ModuleException_1(AllModuleExceptions):
    def __init__(self, message1):
        super(ModuleException_1, self).__init__()
        self.e_string = "Message: {}".format(message1)
        return

class ModuleException_2(AllModuleExceptions):
    def __init__(self, message2):
        super(ModuleException_2, self).__init__()
        self.e_string = "Message: {}".format(message2)
        return

def func_that_raises_exception(arg1, arg2):
    result = arg1 + arg2
    raise ModuleException_1("Something bad happened")

def func(arg1, arg2):

    try:
        result = func_that_raises_exception(arg1, arg2)

    except ModuleException_1:
        raise ModuleException_2("We need to halt main") from None

    return result

pool = multiprocessing.Pool(2)
results = pool.starmap(func, [(1,2), (3,4)])

pool.close()
pool.join()

print(results)

此代码产生此错误:

  

主题Thread-3中的异常:
  追溯(最近的呼叫最后):
  文件“/user/peteoss/encap/Python-3.4.2/lib/python3.4/threading.py”,第921行,在_bootstrap_inner中   self.run()
  文件“/user/peteoss/encap/Python-3.4.2/lib/python3.4/threading.py”,第869行,在运行中
  self._target(* self._args,** self._kwargs)
  文件“/user/peteoss/encap/Python-3.4.2/lib/python3.4/multiprocessing/pool.py”,第420行,在_handle_results中   task = get()
  文件“/user/peteoss/encap/Python-3.4.2/lib/python3.4/multiprocessing/connection.py”,第251行,在recv中   返回ForkingPickler.loads(buf.getbuffer())   TypeError:__ init __()缺少1个必需的位置参数:'message2'

相反,如果我只是调用该函数,它似乎正确处理异常:

print(func(1, 2))

产地:

  

追踪(最近的呼叫最后):
  文件“exceptions.py”,第40行,在   print(func(1,2))
  文件“exceptions.py”,第30行,在func中   从None中提出ModuleException_2(“我们需要暂停main”)   __main __。ModuleException_2

为什么ModuleException_2在进程池中运行时表现不同?

2 个答案:

答案 0 :(得分:10)

问题是你的异常类在__init__方法中有非可选参数,但是当你调用超类__init__方法时,你不会传递这些参数。当您的异常实例被multiprocessing代码取消时,这会导致新的异常。

这是Python异常的一个长期存在的问题,你可以在this bug report中阅读相当多的问题历史(其中一部分基本问题与酸洗异常是固定的,但是不是你要打的部分。

总结一下这个问题:Python的基础Exception类将所有__init__方法接收的参数放入名为args的属性中。这些参数被放入pickle数据中,当流被取消时,它们被传递给新创建的对象的__init__方法。如果Exception.__init__收到的参数数量与子类所期望的数量不同,则会在取消时间时出错。

该问题的解决方法是将自定义异常类在其__init__方法中所需的所有参数传递给超类__init__

class ModuleException_2(AllModuleExceptions):
    def __init__(self, message2):
        super(ModuleException_2, self).__init__(message2) # the change is here!
        self.e_string = "Message: {}".format(message2)

另一种可能的解决方法是根本不调用超类__init__方法(这是上面链接的bug中允许的修复),但由于这通常是子类的不良行为,我不能真的推荐它。

答案 1 :(得分:1)

你的ModuleException_2.__init__在被打结时失败。

我能够通过将签名更改为

来解决问题
class ModuleException_2(AllModuleExceptions):
    def __init__(self, message2=None):
        super(ModuleException_2, self).__init__()
        self.e_string = "Message: {}".format(message2)
        return

但最好看一下Pickling Class Instances以确保干净的实施。