gpt4 book ai didi

python - 键盘中断后执行代码的问题

转载 作者:行者123 更新时间:2023-12-04 13:09:54 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com