【发布时间】: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