I’m running this simple code:
import threading, time
class reqthread(threading.Thread):
def run(self):
for i in range(0, 10):
time.sleep(1)
print('.')
try:
thread = reqthread()
thread.start()
except (KeyboardInterrupt, SystemExit):
print('\n! Received keyboard interrupt, quitting threads.\n')
But when I run it, it prints
$ python prova.py
.
.
^C.
.
.
.
.
.
.
.
Exception KeyboardInterrupt in <module 'threading' from '/usr/lib/python2.6/threading.pyc'> ignored
In fact python thread ignore my Ctrl+C keyboard interrupt and doesn’t print Received Keyboard Interrupt. Why? What is wrong with this code?
Try
Without the call to
time.sleep, the main process is jumping out of thetry...exceptblock too early, so theKeyboardInterruptis not caught. My first thought was to usethread.join, but that seems to block the main process (ignoring KeyboardInterrupt) until thethreadis finished.thread.daemon=Truecauses the thread to terminate when the main process ends.