我正在实现一个多线程程序,其中一个线程从串行端口读取。我在尝试使用KeyboardInterrupt结束程序时遇到了麻烦。现在我只有主线程和从串口读取的线程。代码如下所示:
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"
有时候一切都很好,但有时却没有。这些是一些日志。
为什么这个没有被try-except块捕获?
^CTraceback (most recent call last):
File "bbbDAQ.py", line 147, in <module>
time.sleep(0.1)
KeyboardInterrupt
两个中断,第一个将我们从try-expect块中取出,然后在执行print语句时将另一个中断?
^CTraceback (most recent call last):
File "bbbDAQ.py", line 149, in <module>
print 'Bye Bye'
KeyboardInterrupt
此时我真的很困惑。有人可以解释那里发生了什么以及我错过了什么。
----------- Edit_1 ----------------
我用这个改变了try-except块:
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)
大多数时候程序在按下ctrl-c时会按预期退出,但有时我会得到这个日志:
^CBye Bye
Bye Bye
Exception SystemExit: 0 in <module 'threading' from '/usr/lib/python2.7/threading.pyc'> ignored
异常被解雇两次,这怎么可能?