我不确定是否可以将队列字典作为参数传递给进程。如果只能作为 kwargs 实现,那该怎么做呢?
from multiprocessing import Process, Queue
class WordsManager:
def __init__(self, my_dict):
self.dict = my_dict
def run(self):
pass
def words_worker(my_dict):
worker = WordsManager(my_dict)
worker.run()
def start_job_manager():
my_dict = {}
for language in ('en', 'de', 'es'):
my_dict[language] = Queue()
words_manager = {'process': None, 'my_dict': my_dict}
words_manager["process"] = Process(target=words_worker, args=(words_manager['my_dict']))
words_manager["process"].daemon = True
words_manager["process"].start()
return words_manager
start_job_manager()
错误是:
Process Process-4:
Traceback (most recent call last):
File "/home/antonio/python/lib/python3.4/multiprocessing/process.py", line 254, in _bootstrap
self.run()
File "/home/antonio/python/lib/python3.4/multiprocessing/process.py", line 93, in run
self._target(*self._args, **self._kwargs)
TypeError: words_worker() takes 1 positional argument but 3 were given
请您参考如下方法:
问题出在您传递给进程的参数中:
args=(words_manager['my_dict'])
大括号不会被解释为元组,因此您不会将一系列参数传递给 args。相反,您应该通过将 , 放在末尾来显式创建一个 1 元素元组:
args=(words_manager['my_dict'],)
来自Python Docs :
A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective.
