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

Python Multiprocessing - How to pass kwargs to function?(Python 多处理 - 如何将 kwargs 传递给函数?)
本文介绍了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 传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

build conda package from local python package(从本地 python 包构建 conda 包)
How can I see all packages that depend on a certain package with PIP?(如何使用 PIP 查看依赖于某个包的所有包?)
How to organize multiple python files into a single module without it behaving like a package?(如何将多个 python 文件组织到一个模块中而不像一个包一样?)
Check if requirements are up to date(检查要求是否是最新的)
How to upload new versions of project to PyPI with twine?(如何使用 twine 将新版本的项目上传到 PyPI?)
Why #egg=foo when pip-installing from git repo(为什么从 git repo 进行 pip 安装时 #egg=foo)