With 子句用于 Python 中的多处理
With Clause for Multiprocessing in Python
在 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
部分的底部查看示例。
虽然它比 OP 要求的要多,但如果您想要同时适用于 Python 2 和 Python 3 的东西,您可以使用:
# For python 2/3 compatibility, define pool context manager
# to support the 'with' statement in Python 2
if sys.version_info[0] == 2:
from contextlib import contextmanager
@contextmanager
def multiprocessing_context(*args, **kwargs):
pool = multiprocessing.Pool(*args, **kwargs)
yield pool
pool.terminate()
else:
multiprocessing_context = multiprocessing.Pool
之后,您可以使用常规 Python 3 方式进行多处理,而不管您使用的 Python 是哪个版本。例如:
def _function_to_run_for_each(x):
return x.lower()
with multiprocessing_context(processes=3) as pool:
results = pool.map(_function_to_run_for_each, ['Bob', 'Sue', 'Tim']) print(results)
将在 Python 2 或 Python 3 中工作。
在 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
部分的底部查看示例。
虽然它比 OP 要求的要多,但如果您想要同时适用于 Python 2 和 Python 3 的东西,您可以使用:
# For python 2/3 compatibility, define pool context manager
# to support the 'with' statement in Python 2
if sys.version_info[0] == 2:
from contextlib import contextmanager
@contextmanager
def multiprocessing_context(*args, **kwargs):
pool = multiprocessing.Pool(*args, **kwargs)
yield pool
pool.terminate()
else:
multiprocessing_context = multiprocessing.Pool
之后,您可以使用常规 Python 3 方式进行多处理,而不管您使用的 Python 是哪个版本。例如:
def _function_to_run_for_each(x):
return x.lower()
with multiprocessing_context(processes=3) as pool:
results = pool.map(_function_to_run_for_each, ['Bob', 'Sue', 'Tim']) print(results)
将在 Python 2 或 Python 3 中工作。