分析多进程Python脚本时出现神秘的pickle错误

Eri*_* Yu 6 python parallel-processing profiling

multiprocessing正在使用模块,我正在使用UpdateMessage对象(我自己的类),通过multiprocessing.Queue对象发送,在进程之间进行通信.这是类:

class UpdateMessage:
    def __init__(self, arrayref, rowslice, colslice, newval):
        self.arrayref = arrayref
        self.rowslice = rowslice
        self.colslice = colslice
        self.newval = newval
    def do_update(self):
        if self.arrayref == 'uL':
            arr = uL
        elif self.arrayref == 'uR':
            arr = uR
        else:
            raise Exception('UpdateMessage.arrayref neither uL nor uR')
        arr[self.rowslice, self.colslice] = self.newval
Run Code Online (Sandbox Code Playgroud)

当我运行脚本时,它完全正常.但是,当我使用cProfile或运行它时profile,它会出现以下错误:

_pickle.PicklingError: Can't pickle <class '__main__.UpdateMessage'>: attribute lookup __main__.UpdateMessage failed
Run Code Online (Sandbox Code Playgroud)

它似乎试图挑选课程,但我不明白为什么会发生这种情况.我的代码没有这样做,没有它就可以正常工作,所以它可能就是multiprocessing模块.但为什么需要腌制UpdateMessage,我该如何修复错误呢?

编辑:这是发送的代码的一部分UpdateMessage(脚本的多个部分执行此操作,但所有都以相同的方式):

msg = UpdateMessage(uLref, refer[0] + marker[0] - 2,
                    slice(uL.shape[1]), ustar.copy())
queue.put(msg)
Run Code Online (Sandbox Code Playgroud)

回溯不是很有用:

Traceback (most recent call last):
  File "/usr/lib/python3.2/multiprocessing/queues.py", line 272, in _feed
    send(obj)
Run Code Online (Sandbox Code Playgroud)

Use*_*ser 5

我不知道您的流程如何,但是:

'__main__.UpdateMessage'
Run Code Online (Sandbox Code Playgroud)

指的是启动模块中的 UpdateMessage。

当另一个进程不是使用类的 Module 启动时UpdateMessage,UpdateMessage 将不可用。

您必须导入包含 UpdateMessage 的模块 UpdateMessage.__module__ is not '__main__'

然后 Pickle 也可以在其他程序中找到 UpdateMessage。

我建议__main__.py看起来像这样:

import UpdateMessage_module

UpdateMessage_module.main()
Run Code Online (Sandbox Code Playgroud)


the*_*orn 0

我假设您的班级上的酸洗尝试发生在您的班级被发送到另一个进程之前。最简单的解决方案可能只是在你的类上显式地实现 pickle 协议......