我正在尝试multiprocess.apply_async
同时接受*args
和**kwargs
。文档表明这可能与调用序列有关:
apply_async(func[, args[, kwds[, callback]]])
但我不知道如何使调用语法正确。用最小的例子:
from multiprocessing import Pool
def f(x, *args, **kwargs):
print x, args, kwargs
args, kw = (), {}
print "# Normal call"
f(0, *args, **kw)
print "# Multicall"
P = Pool()
sol = [P.apply_async(f, (x,), *args, **kw) for x in range(2)]
P.close()
P.join()
for s in sol: s.get()
这可以按预期工作,给出输出
# Normal call
0 () {}
# Multicall
0 () {}
1 () {}
例如,当 args 不是空元组时,args = (1,2,3)
单个调用有效,但多处理解决方案给出:
# Normal call
0 (1, 2, 3) {}
# Multicall
Traceback (most recent call last):
File "kw.py", line 16, in <module>
sol = [P.apply_async(f, (x,), *args, **kw) for x in range(2)]
TypeError: apply_async() takes at most 5 arguments (6 given)
例如,使用 kwargs 参数kw = {'cat':'dog'}
# Normal call
0 () {'cat': 'dog'}
# Multicall
Traceback (most recent call last):
File "kw.py", line 15, in <module>
sol = [P.apply_async(f, (x,), *args, **kw) for x in range(2)]
TypeError: apply_async() got an unexpected keyword argument 'cat'
我该如何正确包装multiprocess.apply_async
?