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

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

问题描述

如何使用 Python 的多处理将字典传递给函数?文档: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 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 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 多处理 - 如何将 kwargs 传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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