【问题标题】:Python multiprocessing - Passing a list of dicts to a poolPython多处理 - 将字典列表传递给池
【发布时间】:2017-10-12 23:03:27
【问题描述】:

这个问题可能是重复的。但是,我阅读了很多关于这个主题的内容,但没有找到与我的情况相匹配的内容 - 或者至少,我不理解它。

很抱歉给您带来不便。

我正在尝试做的事情相当普遍,将 kwargs 列表传递给 pool.starmap(),以实现多处理。

这是我的简化案例:

def compute(firstArg, **kwargs): # A function that does things
    # Fancy computing stuff...
    # Saving to disk...
    return True

if __name__ ==  '__main__':
    args = [{
        'firstArg': "some data",
        'otherArg': "some other data"
        'andAnotherArg': x*2
    } for x in range(42)]

    pool = Pool(4)
    pool.starmap(compute, args)
    pool.close()
    pool.terminate()

我认为 starmap() 将解压 dict 并将其作为关键字 args 传递给 compute(),但查看 source code(另见 l.46),它只发送键(或值?)。

所以它提出了:

TypeError: compute() takes 1 positional argument but 3 were given

这必须是一种清晰、直接的方式来做到这一点...任何帮助将不胜感激。

这是一个非常相似的问题:Python Multiprocessing - How to pass kwargs to function?

【问题讨论】:

    标签: python multiprocessing pool


    【解决方案1】:

    你可以使用一个小代理功能:

    def proxy(Dict):
        return compute(**Dict)
    
    pool.map(proxy, args)
    

    或者,因为您不需要 proxy 函数污染命名空间:

    pool.map(lambda Dict: compute(**Dict), args)
    

    【讨论】:

    • 太棒了!只是在 lambda 中使用它,这很完美。感谢您的帮助!
    • 有没有解压dict的列表?我需要传递整个 dict,而不仅仅是 kwargs。谢谢!
    • 我有一个这样的函数: def proc(arg): os.system(arg['args'] % (arg['exe'], arg['env'], arg[' taskName'], arg['searchPath'])) 并希望在池中传递字典列表。
    • @New2Python,只是不要解压单个字典:pool.map(proc, args)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 2019-02-11
    • 2020-03-23
    • 2016-12-06
    • 2020-07-24
    • 2016-12-22
    相关资源
    最近更新 更多