Search code examples
python-3.xwindows-10msvcrt

How to Detect 'ESC' keypress while expecting input() from user


I tried using

if msvcrt.kbhit():
  key_stroke = msvcrt.getch()

  if key_stroke==chr(27).encode(): #b'\x1b'
    print ("Esc key pressed")
    sys.exit()`

before and after the data=input('Enter a value:') but the Esc key_stroke not getting detected

That is, while expecting an input from user with input() function, if the user press Esc key, I want to do sys.exit()


Solution

  • Try this:

    import sys
    import msvcrt
    def func():
        print ('Enter user input:')
        while True:
            if msvcrt.kbhit():
                key_stroke = msvcrt.getche()
                if key_stroke==chr(27).encode():
                    print ("Esc key pressed")
                    sys.exit()
                else:
                    #print (str(key_stroke).split("'")[1],"key pressed")
                    i=str(key_stroke).split("'")[1]+input()
                    print ("User input:",i)
                                
    func()
    

    Note: I am using getche instead of getch, it is similar to getch but prints the key that is pressed.