3

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?

Hrvoje T
  • 3,365
  • 4
  • 28
  • 41
  • 1
    You can use `curses` module https://docs.python.org/3/library/curses.html – Mazdak Apr 20 '15 at 06:34
  • `curses` is (as far as possible) OS independent, and supplies the `getch()` function for a `Windows` object. It returns a single keystroke, with or without waiting, even ESC or CTRL-x. You can suppress the Ctrl-Break function etc. The package is called ncurses. – user1016274 Apr 20 '15 at 08:38
  • @HansThen Thank you, that solved my issue. I added that classes and then getch = _Getch() char = getch.impl() – Hrvoje T Apr 20 '15 at 08:53
  • @HansThen How can I recognize if enter key is pressed? I covered ESC with u'001b' but don't know unicode for enter if there is one? – Hrvoje T Apr 22 '15 at 17:30

1 Answers1

-2

To read and input without the user having to press enter you could use the msvcrt module. You can find more information about it here.

caj15
  • 1
  • 1
  • Thank you for your answer, but bash is Linux terminal and I think 'msvcrt' is for Windows/DOS only. – Hrvoje T Apr 20 '15 at 08:22