给出AttributeError的多处理示例 [英] Multiprocessing example giving AttributeError

查看:129
本文介绍了给出AttributeError的多处理示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在代码中实现多处理,因此,我认为我将从一些示例开始学习.我使用了文档中找到的第一个示例.

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]))

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

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.

推荐答案

此问题似乎是multiprocessing.Pool的设计特征.请参见 https://bugs.python.org/issue25053 .由于某些原因,Pool并不总是与未在导入模块中定义的对象一起使用.因此,您必须将函数编写到其他文件中,然后导入模块.

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.

文件: defs.py

def f(x):
    return x*x

文件: 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.

这篇关于给出AttributeError的多处理示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆