pythonpython-3.xinputkeyboard-events

How to detect esc while input in python


I am doing an input script in python, and I want to detect the ESc button is pressedwhile input. I tried to to use keyoard detector but it does not work. Here is what I did:

import msvcrt

# validating input
def enteringMessage(message):
    while True:

        try:
            # Convert the input to an integer
            message = int(message)

            # Check if the value is within the range
            assert 1 <= message <= 24
            return message  # Return the valid value
        except ValueError:
            # Handle non-numerical input
            message = input('What day is it [1,24] ?\n')
        except AssertionError:
            # Handle out-of-range values
            message = input('What day is it [1,24] ?\n')

aborted = False

while not aborted:
    day = enteringMessage(input('What day is it [1,24] ?\n'))
    if msvcrt.kbhit() and msvcrt.getch() == b'\x1b':
        aborted = True
        break
    humorOftheDay = 'xxxxx'  #I fixed this for simplification purpose
    print("Joke of December ", day, ": ")
    print(humorOftheDay)

I tried to use libary msvcrt to detect and modify the aborted variable to stop the input loop, but when I ran in terminal, it does not work.

Code written in Python, version 3.9

Can you help me out. Thank you in advance.


Solution

  • With msvcrt.getch you'll have to implement your own input function to deal with key presses (including special ones such as backspaces) and translating them into a string of characters.

    If you can install the pynput library, an easier approach would be to listen to the on_press keyboard event with a handler that terminates the process if the key of the event is ESC:

    import os
    from pynput import keyboard
    
    def on_press(key):
        if key == keyboard.Key.esc:
            os._exit(0)
    
    keyboard.Listener(on_press=on_press).start()
    
    while True:
        print(f'You entered: {input("Enter something: ")}')