Используйте модуль 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()