9

我正在尝试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

4

1 回答 1

22

您不必明确使用*和。**只需传递 tuple 和 dict 并让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只有一个参数,在调用时将其解包,func并且kwargs一个参数并以相同的方式处理。另请注意,在 之后不可能有其他参数**kwargs

>>> def test(**kwargs, something=True): pass

  File "<stdin>", line 1
    def test(**kwargs, something=True): pass
                     ^
SyntaxError: invalid syntax
于 2013-04-25T21:02:01.517 回答