Sunday, 15 September 2013

Treat escape key as an action instead of a character in Python input

Treat escape key as an action instead of a character in Python input

In a command-line application, I'm using the following code to ask the
user a yes/no question (it just uses the standard input):
# Taken from http://code.activestate.com/recipes/577058-query-yesno/
# with some personal modifications
def yes_no(question, default=True):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is one of "yes" or "no".
"""
valid = {"yes":True, "y":True, "ye":True,
"no":False, "n":False }
if default == None:
prompt = " [y/n] "
elif default == True:
prompt = " [Y/n] "
elif default == False:
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while 1:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == '':
return default
elif choice in valid.keys():
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "\
"(or 'y' or 'n').\n")
If the user types yes (or an equivalent) the function returns True, and no
returns False. If they just press Enter, the default value is chosen.
However, if user presses ESC on their keyboard, it gets treated as a
character. Is there instead a way to cause the function to return False if
that key is pressed? The few results I have found in my own searches seem
overly complicated or only work on some operating systems.

No comments:

Post a Comment