简体   繁体   English

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

[英]How to pass a dictionary of Queues to multiprocessing.Process

I am not sure if it is possible to pass an dictionary of Queues as argument to a Process.我不确定是否可以将队列字典作为参数传递给进程。 If it is only possible as kwargs, how can it be done?如果只能作为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()

The error is:错误是:

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

The problem is in the arguments you pass to the process:问题在于您传递给进程的参数:

args=(words_manager['my_dict'])

The braces are not interpreted as tuple, so you're not passing a sequence of arguments to the args .大括号不会被解释为元组,因此您不会将一系列参数传递给args Instead you should explicitly create a 1-element tuple by placing , at the end:相反,您应该通过在末尾放置,来显式创建一个 1 元素元组:

args=(words_manager['my_dict'],)

From the Python Docs :来自Python 文档

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these.一个特殊的问题是包含 0 或 1 个项目的元组的构造:语法有一些额外的怪癖来适应这些。 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.丑陋,但有效。

If I use a comma after the element, it runs properly如果我在元素后使用逗号,它会正常运行

args=(words_manager['my_dict'],)

I suppouse that without the comma, Python interprets each value from the dictionary as an argument, but with the comma it is treated as a tuple with words_manager['my_dict'] as a sole argument.我假设没有逗号,Python 将字典中的每个值解释为一个参数,但使用逗号,它被视为一个元组,以 words_manager['my_dict'] 作为唯一参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM