簡體   English   中英

如何編寫一個將另一個函數及其參數作為輸入,在線程中運行並在執行后銷毀線程的函數?

[英]How to write a function that takes another function and its arguments as input, runs it in a thread and destroys thread after execution?

我正在嘗試在micropython中編寫一個函數,該函數采用另一個函數的名稱以及參數和關鍵字參數,創建一個線程來運行該函數,並在函數返回后自動退出該線程。

要求是必須在此線程中運行的函數可能根本沒有參數/關鍵字參數,或者可能具有可變數量的參數。

到目前為止,我嘗試了:

import _thread

def run_main_software():
    while True:
        pass


def run_function(function, arguments, kwarguments):
    def run_function_thread(function, args, kwargs):
        function(*args, **kwargs)
        _thread.exit()

    _thread.start_new_thread(run_function_thread, (function, arguments, kwarguments))


_thread.start_new_thread(run_main_software, ())


def test_func(thingtoprint):
    print(thingtoprint)

但是,當我嘗試運行此命令時,我得到:

>>> run_function(test_func, "thingtoprint")
>>> Unhandled exception in thread started by <function run_function_thread at 0x2000fb20>
Traceback (most recent call last):
  File "<stdin>", line 44, in run_function_thread
AttributeError: 'NoneType' object has no attribute 'keys'

如果我通過所有三個參數:

>>> run_function(test_func, "Print this!", None)
>>> Unhandled exception in thread started by <function run_function_thread at 0x20004cf0>
Traceback (most recent call last):
  File "<stdin>", line 48, in run_function_thread
TypeError: function takes 1 positional arguments but 11 were given

我在這里做錯了什么?

謝謝!

編輯:我試圖通過Giacomo Alzetta的建議與(“ Print this!”,)一起運行,我得到了:

>>> run_function(test_func, ("Print this!", ), None)
>>> Unhandled exception in thread started by <function run_function_thread at 0x20003d80>
Traceback (most recent call last):
  File "<stdin>", line 44, in run_function_thread
AttributeError: 'NoneType' object has no attribute 'keys'

編輯2:如果我這樣做,它將起作用:

>>> run_function(test_func, ("Print this!", ), {})
>>> Print this!

問題在於,在第一種情況下,我缺少一個非可選參數(kwarguments)。 因此** kwargs無法找到要迭代的任何鍵,從而導致錯誤:

AttributeError: 'NoneType' object has no attribute 'keys'

在第二種情況下,我明確地將None傳遞給** kwargs而不是字典。 但是,在這里,它注意到我將字符串傳遞給* args而不是元組。 因此,* args本質上遍歷字符串,並將字符串中的每個字符作為不同的參數。 結果是:

TypeError: function takes 1 positional arguments but 11 were given

在第三種情況下,我確實將一個元組傳遞給* args,但是該錯誤與第一種情況基本相同。

解決方案是將元組傳遞給* args,並將空字典傳遞給** kwargs,如下所示:

>>> run_function(test_func, ("Print this!", ), {})
>>> Print this!

暫無
暫無

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

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