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

标签 python lcd

我为这个 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/

相关文章:

python - 测试列表是否包含某个范围内的数字

Arduino LCD仅在底行显示黑框

c - if then语句c编程

c - 将 16x2 LCD 与 SPI 连接,将字符放入第二行

arduino - setCursor(X,Y) 坐标的含义

c - 打破 while 循环并重新启动代码

python - 如何使用带锁的多处理队列

python - 设置奇怪的行为(python)

python 有 glob 仅返回 5 个最近的文件匹配

python - 使用正确的分页从twitter获取用户的所有followers_id