如何使用Python的多处理将字典传递给函数?文档:https://docs.python.org/3.4/library/multiprocessing.html#reference说要传递字典,但我一直在
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)
答案 0 :(得分:13)
当我运行你的代码时,我得到了一个不同的错误:
TypeError: fp() takes at most 3 arguments (5 given)
我通过打印args和kwargs并将方法更改为fp(*args, **kwargs)
来调试,并注意到" bob _"被传递为一系列字母。似乎用于args
的括号是可操作的,实际上并没有给你一个元组。将它更改为列表,然后传递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)