python - 使用带有生成器函数的 python 多处理模块时出错。

标签 python multiprocessing generator yield

谁能解释一下下面的代码有什么问题

from multiprocessing import Pool
def sq(x):
    yield x**2
p = Pool(2)

n = p.map(sq, range(10))

出现以下错误

MaybeEncodingError Traceback (most recent call last) in () 5 p = Pool(2) 6 ----> 7 n = p.map(sq, range(10))

/home/devil/anaconda3/lib/python3.4/multiprocessing/pool.py in map(self, func, iterable, chunksize) 258 in a list that is returned. 259 ''' --> 260 return self._map_async(func, iterable, mapstar, chunksize).get() 261 262 def starmap(self, func, iterable, chunksize=None):

/home/devil/anaconda3/lib/python3.4/multiprocessing/pool.py in get(self, timeout) 606 return self._value 607 else: --> 608 raise self._value 609 610 def _set(self, i, obj):

MaybeEncodingError: Error sending result: '[, ]'. Reason: 'TypeError("can't pickle generator objects",)'

非常感谢。

最佳答案

您必须在此处使用函数 而不是生成器。意思是:通过return改变yield,将sq转换为一个函数。 Pool 不能与生成器一起使用。

此外,当尝试在 Windows 上创建工作版本时,我收到了一条奇怪的重复错误消息。

Attempt to start a new process before the current process
has finished its bootstrapping phase.

This probably means that you are on Windows and you have
forgotten to use the proper idiom in the main module:

if __name__ == '__main__':

从字面上引用我得到的评论,因为它是不言自明的:

the error on windows is because each process spawns a new python process which interprets the python file etc. so everything outside the "if main block" is executed again"

为了便于移植,您必须在运行此模块时使用 __name__=="__main__":

from multiprocessing import Pool

def sq(x):
    return x**2

if __name__=="__main__":
    p = Pool(2)
    n = p.map(sq, range(10))
    print(n)

结果:

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

编辑:如果你不想预先存储值,你可以使用imap:

n = p.imap(sq, range(10))

n 现在是生成器对象。为了使用这些值(并激活实际处理),我强制迭代列表并得到与上面相同的结果:

print(list(n))

请注意,文档表明 imapmap 慢得多。

关于python - 使用带有生成器函数的 python 多处理模块时出错。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42041000/

相关文章:

python - 如果满足条件,则从列表列表中删除列表

c++ - 如何从 python SWIG 包装器向下转换 c++ 对象?

python - 检测 postgresql 数据库中子网重叠的最佳方法

flutter - Flutter StreamBuilder从先前的生成器流中生成快照

python - 使用生成器作为 sorted() 的输入而不是列表理解是否值得

python - 值错误: I/O operation on closed file when using **generator** over **list**

python - 如何在反向传播算法中使用链式法则的结果中的矩阵相乘

python - python 中的 Selenium 和多处理

Python 3.6 Tkinter 和多重处理

python - Twisted DeferredList 仅在一半的时间内运行其回调