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

2024-09-28 19:23:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用multiprocessing模块,并使用通过multiprocessing.Queue对象发送的UpdateMessage对象(我自己的类)在进程之间通信。课程如下:

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

当我运行脚本时,它运行得非常好。但是,当我使用cProfileprofile运行它时,它会给出以下错误:

^{pr2}$

它似乎是想把班里的人弄得一团糟,但我不明白为什么会这样。我的代码不能做到这一点,没有它它也能正常工作,所以它可能是multiprocessing模块。但是为什么它需要pickle UpdateMessage,我如何修复错误?在

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

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

回溯不是很有用:

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

Tags: 模块对象self脚本def错误ulmultiprocessing
3条回答

我不知道你的流程是怎样的,但是:

'__main__.UpdateMessage'

引用已启动模块中的更新消息。在

当另一个进程不是用UpdateMessage类的模块启动时,UpdateMessage将不可用。在

您必须导入包含UpdateMessage的模块,以便 UpdateMessage.__module__ is not '__main__'。在

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

我建议__main__.py如下所示:

^{pr2}$

我假设在你的类被发送到另一个进程之前对你的类进行酸洗。最简单的解决方案可能就是在类上显式地实现pickle协议。。。在

我遇到了同样的问题,通过在自己的文件中定义要pickle的类来解决这个问题。在

相关问题 更多 >