简体   繁体   English

Python多处理 - 如何将kwargs传递给函数?

[英]Python Multiprocessing - How to pass kwargs to function?

How do I pass a dictionary to a function with Python's Multiprocessing? 如何使用Python的多处理将字典传递给函数? The Documentation: https://docs.python.org/3.4/library/multiprocessing.html#reference says to pass a dictionary, but I keep getting 文档: https//docs.python.org/3.4/library/multiprocessing.html#reference说传递字典,但我一直在

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

Here's the code: 这是代码:

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)

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. 我通过打印args和kwargs并将方法更改为fp(*args, **kwargs)调试,并注意到“bob_”作为一个字母数组传入。 It seems that the parentheses used for args were operational and not actually giving you a tuple. 似乎用于args的括号是可操作的,实际上并没有给你一个元组。 Changing it to the list, then also passing in numList as a keyword argument, made the code work for me. 将它更改为列表,然后将numList作为关键字参数传递,使代码适合我。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM