我已经多次研究过这个问题,但还没有找到适合我的情况或我理解的解决方法,所以请多多包涵。
基本上,我有一个层次结构的功能组织,这阻止了我在顶层进行多处理。不幸的是,我不相信我可以改变程序的布局——因为我需要在初始输入后创建的所有变量。
例如,假设我有这个:
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
序列化程序而不是 pickle
。 dill
可以在 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/