Python Multiprocessing-如何将kwargs传递给函数? [英] Python Multiprocessing - How to pass kwargs to function?

查看:605
本文介绍了Python Multiprocessing-如何将kwargs传递给函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Python的Multiprocessing将字典传递给函数?文档: https://docs.python.org/3.4/library/multiprocessing. html#reference 说要通过字典,但我不断得到

How do I pass a dictionary to a function with Python's Multiprocessing? The Documentation: https://docs.python.org/3.4/library/multiprocessing.html#reference says to pass a dictionary, but I keep getting

TypeError: fp() got multiple values for argument 'what'

代码如下:

from multiprocessing import Pool, Process, Manager

def fp(name, numList=None, what='no'):
        print ('hello %s %s'% (name, what))
        numList.append(name+'44')

if __name__ == '__main__':

    manager = Manager()

    numList = manager.list()
    for i in range(10):
        keywords = {'what':'yes'}
        p = Process(target=fp, args=('bob'+str(i)), kwargs={'what':'yes'})
        p.start()
        print("Start done")
        p.join()
        print("Join done")
    print (numList)

推荐答案

当我运行您的代码时,出现了另一个错误:

When I ran your code, I got a different error:

TypeError: fp() takes at most 3 arguments (5 given)

我通过打印args和kwargs并将方法更改为fp(*args, **kwargs)进行调试,并注意到"bob_"作为字母数组传入.似乎用于args的括号是可操作的,实际上并没有给您一个元组.将其更改为列表,然后还将numList作为关键字参数传入,使代码对我有用.

I debugged by printing args and kwargs and changing the method to fp(*args, **kwargs) and noticed that "bob_" was being passed in as an array of letters. It seems that the parentheses used for args were operational and not actually giving you a tuple. Changing it to the list, then also passing in numList as a keyword argument, made the code work for me.

from multiprocessing import Pool, Process, Manager

def fp(name, numList=None, what='no'):
    print ('hello %s %s' % (name, what))
    numList.append(name+'44')

if __name__ == '__main__':

    manager = Manager()

    numList = manager.list()
    for i in range(10):
        keywords = {'what': 'yes', 'numList': numList}
        p = Process(target=fp, args=['bob'+str(i)], kwargs=keywords)
        p.start()
        print("Start done")
        p.join()
        print("Join done")
    print (numList)

这篇关于Python Multiprocessing-如何将kwargs传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆