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

谁说胖子不能爱 提交于 2019-12-03 13:13:25

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

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

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. rewrite your code like this to eliminate the with statement:

    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. as pointed out in the comments, use 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)))
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!