Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 有没有一种方法可以编写命令以中止正在运行的函数调用?_Python_Tkinter_Abort - Fatal编程技术网

Python 有没有一种方法可以编写命令以中止正在运行的函数调用?

Python 有没有一种方法可以编写命令以中止正在运行的函数调用?,python,tkinter,abort,Python,Tkinter,Abort,我有一个小部件,它测量经过的时间,然后在一定的持续时间后,它执行一个命令。但是,如果小部件被保留,我希望它中止此函数调用,而不执行该命令 我该怎么办 使用threading模块并启动一个新线程来运行该函数 只中止函数是个坏主意,因为您不知道是否在危急情况下中断了线程。您应该像这样扩展您的函数: import threading class WidgetThread(threading.Thread): def __init__(self): threading.Th

我有一个小部件,它测量经过的时间,然后在一定的持续时间后,它执行一个命令。但是,如果小部件被保留,我希望它中止此函数调用,而不执行该命令


我该怎么办

使用
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线程,但通常中断线程的方式是通过具有某种线程安全状态对象,您可以从小部件中设置,以及线程代码中的逻辑,用于检查状态对象值的变化并中断线程循环