gpt4 book ai didi

python - 如何将队列字典传递给 multiprocessing.Process

转载 作者:太空宇宙 更新时间:2023-11-04 05:41:03 25 4
gpt4 key购买 nike

我不确定是否可以将队列字典作为参数传递给进程。如果只能作为 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.

关于python - 如何将队列字典传递给 multiprocessing.Process,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33894841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com