##Python关于KeyboardInterrupt的问题

对于按下按键CTRL+C后,程序不停止,led1和led2来回循环。
这样情况下就要加入try: except KeyboardInterrupt as results:
import RPi.GPIO as GPIO
import time
def led2():
# led1=31 # led2=15 # beep=29 # fan=32 # key=33
led1 = 31
led2 = 15
on = True
# 设置引脚使用规则为board
GPIO.setmode(GPIO.BOARD)
# 设置led对应引脚为输出
GPIO.setup(led1, GPIO.OUT)
GPIO.setup(led2, GPIO.OUT)
try:
while True:
GPIO.output(led1, on)
GPIO.output(led2, not on)
time.sleep(0.3)
# 亮灭互换
on = not on
except KeyboardInterrupt as results:
GPIO.output(led1, not on)
GPIO.output(led2, not on)
GPIO.cleanup()
if __name__ == ‘__main__’:
led2()
所以最后循环停止了,程序停止。


在Python中,当按下CTRL+C时,如果未捕获,程序不会立即停止。为了解决这个问题,可以使用try-except块来处理KeyboardInterrupt异常。这样,当收到键盘中断信号时,程序会进入except块,执行相应的清理操作,并使程序能够优雅地停止。
6992

被折叠的 条评论
为什么被折叠?



