In a command-line application, I'm using the following code (from Andreas Renberg) 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):
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 True:
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 ↵ Return, the default value is chosen.
However, if the user presses Esc, 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.