我有一个小部件可以测量已用时间,然后在一段时间后它会执行一个命令。但是,如果小部件已离开,我想让它中止此函数调用,而不是执行该命令。有没有办法编写一个命令,以便中止正在运行的函数调用?
我该如何解决这个问题?
我有一个小部件可以测量已用时间,然后在一段时间后它会执行一个命令。但是,如果小部件已离开,我想让它中止此函数调用,而不是执行该命令。有没有办法编写一个命令,以便中止正在运行的函数调用?
我该如何解决这个问题?
使用threading
模块并启动一个将运行该功能的新线程。
只要放弃该功能是一个坏主意,因为您不知道是否在危急情况下中断线程。你应该像这样扩展你的功能:
import threading
class WidgetThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self._stop = False
def run(self):
# ... do some time-intensive stuff that stops if self._stop ...
#
# Example:
# while not self._stop:
# do_somthing()
def stop(self):
self._stop = True
# Start the thread and make it run the function:
thread = WidgetThread()
thread.start()
# If you want to abort it:
thread.stop()
为什么不使用线程并停止它?我不认为有可能在一个单线程程序中拦截函数调用(如果没有某种信号或中断)。
另外,针对您的具体问题,您可能需要引入一个标志并在命令中检查该标志。
不知道python线程,但总的来说,你中断一个线程的方式是通过让某种线程安全的状态对象,你可以从widget中设置,以及线程代码中的逻辑来检查状态的变化对象值和突破线程循环。