如何在Python多进程池中使用关键字参数的apply_async方法

23

我正在尝试掌握Python的多进程模块,具体来说是Poolapply_async方法。我试图使用参数和关键字参数调用函数。如果我不使用关键字参数调用函数,那么一切都很好。但是,当我尝试添加一个关键字参数时,我会得到以下错误消息:TypeError: apply_async() got an unexpected keyword argument 'arg2'下面是我运行的测试代码:

#!/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()

我该如何调用函数以使其接受关键字参数?
3个回答

28

将关键字参数放入一个字典(将位置参数放入一个元组):

pool.apply_async(test, (t,), dict(arg2=5))

4

1

Janne的答案在我使用Python 2.7.11时不起作用(不确定原因)。 函数test()接收到的是键(arg2),而不是值(5)。

我通过创建一个test的包装器来解决了这个问题:

def test2(argsDict):
    test(**argsDict)

然后调用
pool.apply_async(test2, (t,), [dict(arg2=5)])

问题是,如果它是一个包装器,我们不需要关键字参数 :) 我也确认测试接收到了该键的问题。 - Ravindranath Akila

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接