我正在尝试让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
发布于 2013-04-26 05:02:02
您不必显式地使用*和**。只需传递元组和字典,并让apply_async将其解包:
from multiprocessing import Pool
def f(x, *args, **kwargs):
print x, args, kwargs
args, kw = (1,2,3), {'cat': 'dog'}
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 (1, 2, 3) {'cat': 'dog'}
# Multicall
0 (1, 2, 3) {'cat': 'dog'}
1 (1, 2, 3) {'cat': 'dog'}请记住,在python的文档中,如果一个函数接受*args和**kwargs,那么它的签名就会显式地声明:
the_function(a,b,c,d, *args, **kwargs)在您的案例中:
apply_async(func[, args[, kwds[, callback]]])那里没有*,因此args是one参数,它在调用func时被解包,而kwargs是one参数,并以相同的方式处理。还要注意,在**kwargs之后不能有其他参数
>>> def test(**kwargs, something=True): pass
File "<stdin>", line 1
def test(**kwargs, something=True): pass
^
SyntaxError: invalid syntaxhttps://stackoverflow.com/questions/16224600
复制相似问题