python - 如何在不处于顶层的情况下解决python多处理的 pickle 错误?

标签 python multiprocessing pickle python-multiprocessing

我已经多次研究过这个问题,但还没有找到适合我的情况或我理解的解决方法,所以请多多包涵。

基本上,我有一个层次结构的功能组织,这阻止了我在顶层进行多处理。不幸的是,我不相信我可以改变程序的布局——因为我需要在初始输入后创建的所有变量。

例如,假设我有这个:

import multiprocessing

  def calculate(x):
    # here is where I would take this input x (and maybe a couple more inputs)
    # and build a larger library of variables that I use further down the line

    def domath(y):
      return x * y

    pool = multiprocessing.Pool(3)
    final= pool.map(domath, range(3))

calculate(2)

这会产生以下错误:

Can't pickle <type 'function'>: attribute lookup __builtin__.function failed

我在考虑全局变量,但我担心我必须定义太多,这可能会大大降低我的程序速度。 有没有无需重构整个程序的解决方法?

最佳答案

您可以使用 pathos.multiprocessing,它是 multiprocessing 的一个分支,它使用 dill 序列化程序而不是 pickledill 可以在 python 中序列化几乎任何东西。然后,无需编辑您的代码。

>>> from pathos.multiprocessing import ProcessingPool as Pool
>>> 
>>> def calculate(x):
...   def domath(y):
...     return x*y
...   return Pool().map(domath, range(3))
... 
>>> calculate(2)
[0, 2, 4]

你甚至可以疯狂地使用它……因为大多数东西都是 pickle 的。无需使用纯 multiprocessing 编写奇怪的非 pythonic 解决方案。

>>> class Foo(object):
...   def __init__(self, x):
...     self.x = x
...   def doit(self, y):
...     return ProcessingPool().map(self.squared, calculate(y+self.x))
...   def squared(self, z):
...     return z*z
... 
>>> def thing(obj, y):
...   return getattr(obj, 'doit')(y)
... 
>>> ProcessingPool().map(thing, ProcessingPool().map(Foo, range(3)), range(3))
[[0, 0, 0], [0, 4, 16], [0, 16, 64]]

在此处获取 pathos:https://github.com/uqfoundation

关于python - 如何在不处于顶层的情况下解决python多处理的 pickle 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28821910/

相关文章:

python - 在脚本标签内解析 json var

python - 使用 BeautifulSoup 和 Requests 提取 html 单元格数据

python - 使用多重处理来压缩大量文件

Pyramid 应用程序不会在 View 之间释放内存

python - 为什么 Pandas 在读取 pickle 文件时会尝试导入模块?

python数据框到excel

python - 绘制开始结束时隙 - matplotlib python

python - 使用Sanic和Redis遇到麻烦

python - 如何在Python中并行化嵌套for循环?

python - 为什么 pickle 会使我的 Flask 服务器崩溃?