multithreading - Interrupting a thread in Python with a KeyboardException in the main thread -
i have few classes more or less this:
import threading import time class foo(): def __init__(self, interval, callbacks): self.thread = threading.thread(target=self.loop) self.interval = interval self.thread_stop = threading.event() self.callbacks = callbacks def loop(): while not self.thread_stop.is_set(): #do stuff... callback in self.callbacks(): callback() time.sleep(self.interval) def start(self): self.thread.start() def kill(self): self.thread_stop.set()
which using main thread this:
interval = someinterval callbacks = [some callbacks] f = foo(interval, callbacks) try: f.start() except keyboardinterrupt: f.kill() raise
i keyboardinterrupt kill thread after callbacks have been completed, before loop repeats. ignored , have resort killing terminal process program running in.
i saw idea of using threading.event this post, appears i'm doing incorrectly, , it's making working on project pretty large hassle.
i don't know if may relevant, callbacks i'm passing access data internet , make heavy use of retrying decorator deal unreliable connections.
edit
after everyone's help, loop looks inside foo:
def thread_loop(self): while not self.thread_stop.is_set(): # stuff # call callbacks self.thread_stop.wait(self.interval)
this kind of solution, although isn't ideal. code runs on pythonanywhere , price of account cpu time. i'll have see how uses on course of day constant waking , sleeping of threads, @ least solves main issue
i think problem have try-except
-block around f.start()
, returns immediately, aren't going catch keyboardinterrupt
s after thread started.
you try adding while-loop @ bottom of program this:
f.start() try: while true: time.sleep(0.1) except keyboardinterrupt: f.kill() raise
this isn't elegant solution, should work.
Comments
Post a Comment