I'm new to python and I have a python2.x script that asks a user to enter a choice between answers A, B or C in bash. How can I make the script to quit immediately when only escape key is pressed at that time while waiting for user input?
For now, I have this function. However, after escape key I have to press enter too.
def choice(prompt):
"""
Choose A, B or C
ESC exits script
"""
while True:
char = raw_input(prompt)
if char.encode() == '\x1B': # ESC is pressed
sys.exit("Quitting ...")
elif char.lower() not in ('a', 'b', 'c'):
print("Wrong input. Please try again.")
continue
else:
break
return char
user_choice = choice("\nChoose between A - C: ")
print("You chose %s.") % user_choice.upper()
The code is in UTF-8 and escape key in bash terminal gives me ^[. As I understand msvcrt doesn't work in Linux. Can this be done, so the script works in Windows and Linux?