[Python] KeyboardInterrupt doesn't work as expected in while loop

Discussão em 'Python' iniciado por Stack, Maio 19, 2025.

  1. Stack

    Stack Membro Participativo

    I am writing a program that uses the msvcrt module in python for registering keyboard interaction. A while loop constantly checks whether a key is pressed, and if the user choose to exit the program using Crtl + c it should raise a keyboardinterrupt error causing it to break out of the while loop. The problem is that the program does not catch the keyboardinterrupt, here is the code:

    from msvcrt import kbhit, getch # for sensing and catching keyboard data

    def main():
    while True:
    try:
    if kbhit:
    key = getch()
    handle_keypress(key)
    except KeyboardInterrupt:
    break

    def handle_keypress(key):
    # handles tabs key
    if key == b"\t":
    ...
    # handles enter key
    elif key == b"\r":
    ...
    # handles escape key
    elif key == b"\x1b":
    ...
    # handles space key
    elif key == b" ":
    ...

    main()

    Continue reading...

Compartilhe esta Página