gpt4 book ai didi

python - 属性错误 : 'Pool' object has no attribute '__exit__'

转载 作者:太空狗 更新时间:2023-10-29 21:19:51 26 4
gpt4 key购买 nike

我正在使用 multiprocessing.Pool 执行一些多处理 python 脚本。这些脚本如下所示:

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 时出现此错误:

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

使用Python 2.73.2,报错本质上是一样的:

AttributeError: __exit__

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

最佳答案

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

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 进行测试):

  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()
  2. 正如评论中所指出的,使用 contextlib.closing():

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

关于python - 属性错误 : 'Pool' object has no attribute '__exit__' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27065237/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com