Python 给出 AttributeError 的多处理示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41385708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:52:46  来源:igfitidea点击:

Multiprocessing example giving AttributeError

pythonmultithreading

提问by PiccolMan

I am trying to implement multiprocessing in my code, and so, I thought that I would start my learning with some examples. I used the first example found in this documentation.

我试图在我的代码中实现多处理,因此,我想我会从一些例子开始我的学习。我使用了本文档中的第一个示例。

from multiprocessing import Pool
def f(x):
    return x*x

if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(f, [1, 2, 3]))

When I run the above code I get an AttributeError: can't get attribute 'f' on <module '__main__' (built-in)>. I do not know why I am getting this error. I am also using Python 3.5 if that helps.

当我运行上面的代码时,我得到一个AttributeError: can't get attribute 'f' on <module '__main__' (built-in)>. 我不知道为什么会收到此错误。如果有帮助,我也在使用 Python 3.5。

回答by hr87

This problem seems to be a design feature of multiprocessing.Pool. See https://bugs.python.org/issue25053. For some reason Pool does not always work with objects not defined in an imported module. So you have to write your function into a different file and import the module.

这个问题似乎是 multiprocessing.Pool 的一个设计特性。请参阅https://bugs.python.org/issue25053。出于某种原因,Pool 并不总是与未在导入模块中定义的对象一起使用。因此,您必须将函数写入不同的文件并导入模块。

File: defs.py

文件:defs.py

def f(x):
    return x*x

File: run.py

文件:run.py

from multiprocessing import Pool
import defs

 if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(defs.f, [1, 2, 3]))

If you use print or a different built-in function, the example should work. If this is not a bug (according to the link), the given example is chosen badly.

如果您使用 print 或不同的内置函数,该示例应该可以工作。如果这不是错误(根据链接),则给定的示例选择不当。