【问题标题】:how do I use key word arguments with python multiprocessing pool apply_async如何在 python 多处理池 apply_async 中使用关键字参数
【发布时间】:2013-01-26 10:17:59
【问题描述】:

我正在尝试掌握 python 的多处理模块,特别是 Pool 的 apply_async 方法。我正在尝试使用参数和关键字参数调用函数。如果我在没有 kwargs 的情况下调用该函数,那很好,但是当我尝试添加关键字参数时,我得到: 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()

如何调用函数以使其接受关键​​字参数?

【问题讨论】:

    标签: python multiprocessing threadpool


    【解决方案1】:

    在字典中传递关键字 args(以及在元组中的位置参数):

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

    【讨论】:

      【解决方案2】:

      原答案:python multiprocessing with boolean and multiple arguments

      apply_async 有 args 和 kwds 关键字参数,您可以像这样使用它们:

      res = p.apply_async(testFunc, args=(2, 4), kwds={'calcY': False})
      

      【讨论】:

        【解决方案3】:

        Janne 的回答在 python 2.7.11 中对我不起作用(不知道为什么)。 函数 test() 接收的是键 (arg2),而不是值 (5)。

        我通过在测试周围创建一个包装器来解决这个问题:

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

        然后调用

        pool.apply_async(test2, (t,), [dict(arg2=5)])
        

        【讨论】:

        • 问题是,如果是包装器,我们不需要关键字参数:) 我也确认测试接收密钥的问题
        猜你喜欢
        • 2020-10-30
        • 1970-01-01
        • 1970-01-01
        • 2020-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-02
        • 2019-04-05
        相关资源
        最近更新 更多