I'm implementing a multithreaded program where one of the threads reads from a serial port. I'm having trouble when trying to end the program with KeyboardInterrupt. For now I just have the main thread and the one that reads from the serial port. The code looks like this:
import threading
import time
def reader(name, port, run_event):
while run_event.is_set():
port.read(1)
#Process data...............
if __name__ == "__main__":
run_event = threading.Event()
run_event.set()
port=serial.Serial(port=args.serialPort,baudrate=921600)
port.flush()
port.flushInput()
t1 = threading.Thread(target = timed_output, args = ("Reader",port,run_event))
t1.start()
try:
while 1:
time.sleep(.1)
except KeyboardInterrupt:
print "Bye Bye"
run_event.clear()
t1.join()
port.close()
print "threads successfully closed"
Sometimes everything works fine but other times it does not. Those are some of the logs.
Why is this one not caught by the try-except block?
^CTraceback (most recent call last):
File "bbbDAQ.py", line 147, in <module>
time.sleep(0.1)
KeyboardInterrupt
Two interrupts where the first one takes us out of the try-expect block and then another while executing the print statement?
^CTraceback (most recent call last):
File "bbbDAQ.py", line 149, in <module>
print 'Bye Bye'
KeyboardInterrupt
At this point I am really confused. Can someone explain what happens there and what am I missing.
-----------Edit_1----------------
Ive changed the try-except block with this:
def signal_handler(signal, frame):
print 'Bye Bye'
run_event.clear()
t1.join()
port.close()
sys.exit(0)
signal.signal(signal.SIGINT,signal_handler)
while 1:
time.sleep(0.1)
Most of the times the program exits as expected when ctrl-c is hit, but other times im getting this log:
^CBye Bye
Bye Bye
Exception SystemExit: 0 in <module 'threading' from '/usr/lib/python2.7/threading.pyc'> ignored
Is the exception fired twice, how could this be posible?