AttributeError: 'Pool' object does not have '__exit__' attribute

I am running several python scripts with multiple processes using multiprocessing.Pool. These scenarios are as follows:

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]"

When working 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__'

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

AttributeError: __exit__

Why is this happening and how can I get around this?

+4
source share
1 answer

, multiprocessing.pool ( with) Python 3.3 .

3.3: - . . __enter__() , __exit__() terminate().

, Python, : ( Python 2.6, 2.7, 3.1, 3.2 ):

  • , 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.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)))
    
+13

All Articles