如何编写一个将另一个函数及其参数作为输入,在线程中运行并在执行后销毁线程的函数?

时间:2019-07-01 11:52:26

标签: python multithreading python-multithreading micropython

我正在尝试用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!

1 个答案:

答案 0 :(得分:1)

问题在于,在第一种情况下,我缺少一个非可选参数(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!