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

查看:43
本文介绍了给出 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 .我不知道为什么会收到此错误.如果有帮助,我也使用 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天全站免登陆