pythonlcd

Problems executing code after Keyboardinterrupt


I wrote a super simple thingy for this 20x4 LCD screen and I keep on getting this whenever I Interrupt with crtl + c instead of it executing the code I've placed there. Here's the Error:

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

and here's the code:

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)

Thank you in advance! I think this may be a real simple fix but I'm sadly still a complete novice.


Solution

  • Instead of using the if statement...

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

    Use the try / except statements, which are used to check for errors (Pressing CTRL+C spawns a KeyboardInterrupt error):

    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)