Skip to content
Advertisement

how do I use key word arguments with python multiprocessing pool apply_async

I’m trying to get to grips with pythons multiprocessing module, specifically the apply_async method of Pool. I’m trying to call a function with arguments and keyword arguments. If I call the function without kwargs it’s fine but when I try to add in a keyword argument I get: TypeError: apply_async() got an unexpected keyword argument 'arg2' Below is the test code that I’m running

#!/usr/bin/env python
import multiprocessing
from time import sleep
def test(arg1, arg2=1, arg3=2):
    sleep(5)

if __name__ == '__main__':
    pool = multiprocessing.Pool()
    for t in range(1000):
        pool.apply_async(test, t, arg2=5)
    pool.close()
    pool.join()

How can I call the function so that it accepts keyword arguments?

Advertisement

Answer

Pass the keyword args in a dictionary (and the positional arguments in a tuple):

pool.apply_async(test, (t,), dict(arg2=5))
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement