Is there a way to write a command so that it aborts a running function call?
I have a widget that measures elapsed time, then after a certain duration it does a command. However, if the widget is left I want I want it to abort this function call and not do the command.
How do I go about this开发者_StackOverflow社区?
Use the threading
module and start a new thread that will run the function.
Just abort the function is a bad idea as you don't know if you interrupt the thread in a critical situation. You should extend your function like this:
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()
Why not use threads and stop that? I don't think it's possible to intercept a function call in a single threaded program (if not with some kind of signal or interrupt).
Also, with your specific issue, you might want to introduce a flag and check that in the command.
No idea about python threads, but in general the way you interrupt a thread is by having some sort of a threadsafe state object that you can set from the widget, and the logic in thread code to check for the change in state object value and break out of the thread loop.
精彩评论