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()
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.