How to exit python2.x script on press ESCape

I am new to python and I have a python2.x script that asks the user to enter a choice between A, B, or C answers in bash. How can I get the script to exit right away when only the escape key is pressed at that time, waiting for user input?

At the moment I have this function. However, after the Escape key, you must press the Enter key.

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 the escape key in bash terminal gives me ^ [. As far as I understand, msvcrt doesn't work on Linux. Is it possible to do this to make the script work on Windows and Linux?

+3


source to share


1 answer


To read and enter without having to press enter, you can use a module msvcrt

. You can find more information on this here .



-2


source







All Articles