【问题标题】:Python how to initialize thread with unknown number of arguments?Python如何用未知数量的参数初始化线程?
【发布时间】:2012-07-09 08:19:07
【问题描述】:

在尝试创建线程时,我在将带星号的表达式与固定参数列表结合使用时遇到问题。

考虑以下代码:

the_queue = Queue()

def do_something(arg1, arg2, queue):
    # Do some stuff...
    result = arg1 + arg2

    queue.put(result)

def init_thread(*arguments):
    t = Thread(target=do_something, args=(arguments, the_queue))
    t.start()
    t.join()

init_thread(3,6)

这会引发异常:

TypeError: do_something() takes exactly 3 arguments (2 given)

换句话说,“arguments”元组被评估为一个元组对象(即它没有解包),而 the_queue 被视为第二个参数。

代码需要能够用未知数量的参数初始化调用不同方法的线程,但最后总是会有一个“队列”参数。

有什么方法可以实现吗?在那种情况下,怎么办?如果不是 - 我做错了什么?

谢谢。

编辑:我应该补充一点,以队列作为参数调用“init_thread()”方法不是一个选项,因为我不希望我的其余代码“了解”线程处理程序的工作方式内部...

【问题讨论】:

    标签: python multithreading iterable-unpacking


    【解决方案1】:

    你需要创建一个新的tuple

    t = Thread(target = do_something, args = arguments + (the_queue, ))
    

    【讨论】:

    • 啊,非常感谢。我不知道您可以通过这种方式将一个元组连接到另一个元组。干杯!
    【解决方案2】:

    您还可以解压缩打包的 *arguments 元组,如下所示:

    >>> def Print(*args):
    ...     print('I am prepended to every message!', *args)
    ... 
    >>> Print('This', 'has', 'four', 'arguments')
    I am prepended to every message! This has four arguments
    >>> def Print(*args):
    ...     print('I am prepended to every message!', args)
    ... 
    >>> Print('This', 'has', 'four', 'arguments')
    I am prepended to every message! ('This', 'has', 'four', 'arguments')
    

    所以你看,引用 *agruments,而不是参数,将解包元组。 因此您的代码可能是:

    def init_thread(*arguments):  
        t = Thread(target=do_something, args=(*arguments, the_queue))
        t.start()
        t.join()
    

    【讨论】:

    • 我实际上尝试过先这样写(使用 *arguments 来解包),但在尝试这样做时出现错误。我已经在 python 2.6 和 python 3.2.2 中尝试过。在哪个版本的 Python 中是合法的?这当然是一个有用的功能,我认为在面对我的问题时缺少它......编辑:错误是“只能使用星号表达式作为分配目标”
    • 我不知道。我使用 Python 3.2。快速谷歌在这里发现了一些类似的问题。 stackoverflow.com/questions/3870778/… stackoverflow.com/questions/10967819/… 我想不幸的是还有一组额外的括号。其中一个链接建议的解决方案与此处的第一个答案相同。
    猜你喜欢
    • 2011-01-14
    • 2019-03-30
    • 2016-04-11
    • 2015-06-23
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 2014-04-21
    • 2012-03-02
    相关资源
    最近更新 更多