我为这个 20x4 LCD 屏幕编写了一个 super 简单的东西,每当我用 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)
提前谢谢您!我认为这可能是一个非常简单的修复,但遗憾的是我仍然是一个完全的新手。
最佳答案
而不是使用 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)
关于python - 键盘中断后执行代码时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66581258/