簡體   English   中英

Python如何使用未知數量的參數初始化線程?

[英]Python how to initialize thread with unknown number of arguments?

在嘗試創建線程時,我無法將已加星標的表達式與固定參數列表結合使用。

請考慮以下代碼:

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被認為是第二個參數。

代碼需要能夠使用未知數量的參數初始化調用不同方法的線程,但是最后總是會有一個“queue”參數。

有沒有辦法實現這個目標? 在那種情況下,怎么樣? 如果沒有 - 我做錯了什么?

謝謝。

編輯:我應該補充說,使用隊列作為參數調用“init_thread()”方法不是一個選項,因為我不希望我的其余代碼“了解”線程處理程序如何在內部工作。 。

你需要創建一個新的tuple

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

您也可以解壓縮打包的*參數元組,如下所示:

>>> 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM