键盘中断后执行代码时出现问题

Problems executing code after Keyboardinterrupt

我为这个 20x4 LCD 屏幕写了一个超级简单的东西,每当我用 crtl + c 中断而不是执行我放在那里的代码时,我都会继续得到这个。 这是错误:

CTraceback (most recent call last):
  File "lcd/clock.py", line 25, in <module>
    sleep(1)
KeyboardInterrupt

这是代码:

import drivers
from time import sleep
from datetime import datetime
from subprocess import check_output
display = drivers.Lcd()
display.lcd_backlight(0)
IP = check_output(["hostname", "-I"]).split()[0]
usrinpt = input("Text: ")
while len(usrinpt) > 20:
        print("Too Long")
        usrinpt = input("Text: ")
else:
    display.lcd_backlight(1)
    print("Writing to display")
    while True:
        display.lcd_display_string(str(datetime.now().time().strftime("%H:%M:%S")), 1)
        display.lcd_display_string(str(IP), 2)
        display.lcd_display_string(str("____________________"), 3)
        sleep(1)
        display.lcd_display_string(str(datetime.now().time().strftime("%H:%M:%S")), 1)
        display.lcd_display_string(str(IP), 2)
        display.lcd_display_string(str(usrinpt), 3)
        sleep(1)

        if KeyboardInterrupt:
    # If there is a KeyboardInterrupt (when you press ctrl+c), turn off backlights
            display.lcd_backlight(0)

提前致谢!我认为这可能是一个真正简单的修复,但遗憾的是我仍然是一个完全的新手。

问题是因为您按了 Ctrl + C 而 sleep(1) 是 运行。由于您只是在睡眠后检查键盘中断,因此 Python 不会像往常一样检查异常和错误。你可以用 try... except...:

修复它
while True:
    try:
        display.lcd_display_string(str(datetime.now().time().strftime("%H:%M:%S")), 1)
        display.lcd_display_string(str(IP), 2)
        display.lcd_display_string(str("____________________"), 3)
        sleep(1)
        display.lcd_display_string(str(datetime.now().time().strftime("%H:%M:%S")), 1)
        display.lcd_display_string(str(IP), 2)
        display.lcd_display_string(str(usrinpt), 3)
        sleep(1)
    except KeyboardInterrupt:
        display.lcd_backlight(0)

这里,它会继续执行运行代码,直到遇到KeyboardInterrupt,它会执行display.lcd_backlight(0)

而不是使用 if 语句...

if KeyboardInterrupt:
    # If there is a KeyboardInterrupt (when you press ctrl+c), turn off backlights
    display.lcd_backlight(0)

使用 try / except 语句,用于检查错误(按 CTRL+C 会产生 KeyboardInterrupt 错误):

try:
    display.lcd_backlight(1)
    print("Writing to display")
    while True:
        display.lcd_display_string(str(datetime.now().time().strftime("%H:%M:%S")), 1)
        display.lcd_display_string(str(IP), 2)
        display.lcd_display_string(str("____________________"), 3)
        sleep(1)
        display.lcd_display_string(str(datetime.now().time().strftime("%H:%M:%S")), 1)
        display.lcd_display_string(str(IP), 2)
        display.lcd_display_string(str(usrinpt), 3)
        sleep(1)
except KeyboardInterrupt:
    # If there is a KeyboardInterrupt (when you press ctrl+c), turn off backlights
    display.lcd_backlight(0)