【问题标题】:AttributeError: 'Pool' object has no attribute '__exit__'AttributeError:“池”对象没有属性“__exit__”
【发布时间】:2015-01-19 19:51:57
【问题描述】:

我正在使用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__

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

【问题讨论】:

    标签: python python-2.7 python-multiprocessing python-3.2 python-3.1


    【解决方案1】:

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

    3.3 版中的新增功能:池对象现在支持上下文管理协议 - 请参阅上下文管理器类型。 __enter__() 返回池对象,__exit__() 调用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. 正如 cmets 中所指出的,使用 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 2.7 的解决方案是什么?
    • @AshishKarpe:这两个代码示例也适用于 Python 2.7。您收到错误消息吗?
    • @user1231007 错误同上:AttributeError: 'Pool' object has no attribute 'exit'
    • @AshishKarpe 这很奇怪——我刚刚在两台机器上用 Python 2.6 和 Python 2.7 测试了这两个例子——没有错误消息
    猜你喜欢
    • 2012-12-01
    • 2021-04-19
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多