在Python 2.x和3.0、3.1和3.2中,
multiprocessing.Pool()对象 不是上下文管理器
。您不能在
with语句中使用它们。只有在Python 3.3及更高版本中,您才可以使用它们。从Python
3
multiprocessing.Pool()文档中:
版本3.3中的新增功能
:池对象现在支持上下文管理协议–请参阅上下文管理器类型。__enter__()返回池对象,并__exit__()调用Terminate()。
对于早期的Python版本,您可以使用
contextlib.closing(),但要考虑到此调用
pool.close(),而不是
pool.terminate()。在这种情况下,请手动终止:
from contextlib import closingwith closing(Pool(processes=2)) as pool: pool.map(myFunction, mylist) pool.map(myfunction2, mylist2) pool.terminate()
或创建自己的
terminating()上下文管理器:
from contextlib import contextmanager@contextmanagerdef terminating(thing): try: yield thing finally: thing.terminate()with terminating(Pool(processes=2)) as pool: pool.map(myFunction, mylist) pool.map(myfunction2, mylist2)



