Python Multiprocessing - How to pass kwargs to function?
如何使用Python的多处理将字典传递给函数?文档:https://docs.python.org/3.4/library/multiprocessing.html reference说要通过字典,但我一直在
1 | TypeError: fp() got multiple values for argument 'what' |
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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) |
当我运行您的代码时,出现了另一个错误:
1 | TypeError: fp() takes at most 3 arguments (5 given) |
我通过打印args和kwargs并将方法改为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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) |