I've seen several threads on here about killing python threads in a clean way, but I think I'm having a more fundamental issue. Suppose I have some code that looks like this:
t1 = threading.Thread(target=method1, args=(args1,))
t1.daemon = True
t2 = threading.Thread(target=method2, args=(args2, ))
t2.daemon = True
t1.start()
t2.start()
while True:
time.sleep(1)
I would like for the main thread to notice a Ctrl-C keyboard interrupt, and from there I can handle the termination of the other threads (t1
and t2
) as appropriate given the context. But no matter what I do, I can't get the main thread to catch the KeyboardInterrupt
. I've tried something like this:
try:
while True: time.sleep(100)
except KeyboardInterrupt:
print "Quitting!"
Or something like this:
threads = []
threads.append(t1)
threads.append(t2)
while len(threads) > 0:
try:
threads = [t for t in threads if t is not None and t.isAlive()]
time.sleep(1)
except:
print "Ctrl - C received, kiling"
for t in threads:
t.kill_received = True
But none of these even print the messages in the exception handler, displaying only this:
Exception in thread Thread-3:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/local/lib/python2.7/dist-packages/audioread/gstdec.py", line 149, in run
self.loop.run()
File "/usr/lib/python2.7/dist-packages/gi/overrides/GLib.py", line 576, in run
raise KeyboardInterrupt
KeyboardInterrupt
The main question here is not how to kill t1
and t2
safely (I've got to deal with that too, eventually), but why is the main thread not catching KeyboardInterrupt
here?
Edit: As I've written the examples, I've already tried the approach involving sleeping in a while loop within the try-except block. Any other ideas?