How to use multiprocessing pool.map with multiple arguments?

前端 未结 20 3340
-上瘾入骨i
-上瘾入骨i 2020-11-21 11:24

In the Python multiprocessing library, is there a variant of pool.map which supports multiple arguments?

text = "test"
def         


        
20条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 12:06

    There are many answers here, but none seem to provide Python 2/3 compatible code that will work on any version. If you want your code to just work, this will work for either Python version:

    # 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
    

    After that, you can use multiprocessing the regular Python 3 way, however you like. For example:

    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)
    

    will work in Python 2 or Python 3.

提交回复
热议问题