【问题标题】:How to write a function that takes another function and its arguments as input, runs it in a thread and destroys thread after execution?如何编写一个将另一个函数及其参数作为输入的函数,在线程中运行它并在执行后销毁线程?
【发布时间】:2019-07-01 11:52:26
【问题描述】:

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

【问题讨论】:

  • 您省略了 run_function 的第三个非可选参数,称为 kwarguments
  • @jtlz2 我编辑了这个问题,如果我将 kwarguments 设置为 None 会发生什么。
  • "Print this!" 更改为("Print this!", )
  • @GiacomoAlzetta 还是同样的问题。更新了问题。
  • @SriHarshaPavuluri 好了,您现在可以使用 cmets 为您自己的问题添加答案.... :)

标签: python multithreading python-multithreading micropython


【解决方案1】:

问题在于,在第一种情况下,我缺少一个非可选参数(kwarguments)。所以**kwargs找不到要迭代的key,导致报错:

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!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-25
    • 2012-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多