在 python 3 中,您现在可以像这样使用 with
子句安全地打开文件:
with open("stuff.txt") as f:
data = f.read()
使用这种方法,我不需要担心关闭连接
我想知道我是否可以为多处理做同样的事情。例如,我当前的代码如下所示:
pool = multiprocessing.Pool(processes=multiprocessing.cpu_count())
pool.starmap(function,list)
pool.close()
pool.join()
有什么方法可以使用 with 子句来简化它吗?
最佳答案
with multiprocessing.Pool( ... ) as pool:
pool.starmap( ... )
https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool
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().
您可以在 Pool
部分的底部看到一个示例。
关于python - With 子句用于 Python 中的多处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45718546/