Python 多处理 - 将字典列表传递给池

Python multiprocessing - Passing a list of dicts to a pool

这个问题可能是重复的。但是,我阅读了很多关于这个主题的资料,但没有找到符合我的情况的资料 - 或者至少,我不明白。

抱歉给您带来不便。

我正在尝试做的是相当普遍的,将 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() 会解压字典并将其作为关键字参数传递给 compute(),但是查看 source code(另见 l.46),它只发送键(或值? ).

所以它提高了:

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

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

这是一个非常相似的问题:

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

def proxy(Dict):
    return compute(**Dict)

pool.map(proxy, args)

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

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