Python 如何将args和kwargs传递到多处理池?
如果我有以下功能:Python 如何将args和kwargs传递到多处理池?,python,python-3.x,multiprocessing,Python,Python 3.x,Multiprocessing,如果我有以下功能: def foo(a, b, c=2, d=6): return a + b + c + d 我想与多处理并行 如何传递以下参数1、2、d=10?i、 e.2args和1kwarg 我看到了这篇文章,但它似乎并没有使它实际上是平行的。提供了另一个可能有用的例子,但很难解开 那么: import multiprocessing def foo(a, b, c=2, d=6): return a + b + c + d def foo_callback(res
def foo(a, b, c=2, d=6):
return a + b + c + d
我想与多处理
并行
如何传递以下参数1、2、d=10
?i、 e.2args
和1kwarg
我看到了这篇文章,但它似乎并没有使它实际上是平行的。提供了另一个可能有用的例子,但很难解开 那么:
import multiprocessing
def foo(a, b, c=2, d=6):
return a + b + c + d
def foo_callback(result):
print(result)
def foo_error(error):
raise error
pool = multiprocessing.Pool()
for (a, b, c, d) in ((1, 2, 3, 4),
(2, 4, 6, 8),
(3, 6, 9, 12)):
pool.apply_async(
foo,
args=(a, b),
kwds={"c":c, "d":d},
callback=foo_callback,
error_callback=foo_error
)
pool.close()
pool.join()
其中打印:
10
20
30
Process finished with exit code 0
我猜您希望将KWD作为dict传递。键需要是字符串。使用或异步函数将更简单
from multiprocessing import Pool
def foo(args):
a, b, c, d = args
return a + b + c + d # or just sum(args)
with Pool(processes=80) as pool:
iter = ((1, 2, 3, 4), (2, 4, 6, 8), (3, 6, 9, 12))
results = pool.map(foo, iter)
print(results)
就这些。在这种情况下,我怀疑你能得到比仅仅阅读文档更好的答案。我如何才能摆脱循环,而不将
c
作为参数传递?此外,所有结果都不在列表中,因为它们通常与map
一样,这也令人困惑。你能详细说明一下这个词的用法吗?