AttributeError: 'Pool' 对象没有属性 '__exit__' [英] AttributeError: 'Pool' object has no attribute '__exit__'

查看:66
本文介绍了AttributeError: 'Pool' 对象没有属性 '__exit__'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 multiprocessing.Pool 做一些多处理 Python 脚本.这些脚本如下所示:

I'm doing some multiprocessing python scripts using multiprocessing.Pool. These scripts look like the following:

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    with Pool(processes=4) as pool:         # start 4 worker processes
        print(pool.map(f, range(10)))       # prints "[0, 1, 4,..., 81]"

使用 Python 3.4 运行时,一切正常.但是,当使用 Python 2.63.1 时,我收到此错误:

When running this with Python 3.4, everything is fine. However, when using Python 2.6 or 3.1 I get this error:

AttributeError: 'Pool' object has no attribute '__exit__'

使用 Python 2.73.2,错误基本相同:

Using Python 2.7 or 3.2, the error is essentially the same:

AttributeError: __exit__

为什么会发生这种情况,我该如何规避?

Why does this happen and how can I circumvent this?

推荐答案

文档 表示 multiprocessing.pool 支持 Python 版本 3.3 及更高版本中的上下文管理协议(with 语句).

The documentation says that multiprocessing.pool supports the context management protocol (with statements) in Python version 3.3 and above.

3.3 版中的新功能:池对象现在支持上下文管理协议 - 请参阅上下文管理器类型.__enter__() 返回池对象,__exit__() 调用 terminate().

New in version 3.3: Pool objects now support the context management protocol – see Context Manager Types. __enter__() returns the pool object, and __exit__() calls terminate().

因此您要么需要较新版本的 Python,要么使用以下两种可能性之一更改代码(使用 Python 版本 2.6、2.7、3.1、3.2 测试):

So you either need a newer version of Python, or use one of the two following possibilities changing your code (tested with Python versions 2.6, 2.7, 3.1, 3.2):

  1. 像这样重写代码以消除 with 语句:

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    pool = Pool(processes=4)            # start 4 worker processes
    print(pool.map(f, range(10)))       # prints "[0, 1, 4,..., 81]"
    pool.terminate()

  • 正如评论中所指出的,使用 contextlib.closure():

    from multiprocessing import Pool
    import contextlib
    
    def f(x):
        return x*x
    
    if __name__ == '__main__':
        with contextlib.closing(Pool(processes=4)) as pool:
            print(pool.map(f, range(10)))
    

  • 这篇关于AttributeError: 'Pool' 对象没有属性 '__exit__'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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