0

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.

4

1 回答 1

0

如果你想赶上Esc新闻,你必须实现类似getch方法,一次让你一个角色。

这是一个有效的简单实现。

if platform_is_windows:
    from msvcrt import getch

elif platform_is_posix:
    import sys
    import tty
    import termios

    def getch():
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

然后你只有一个while循环,getch直到你得到一个Escor ↵ Return

注意:我没有指定确定平台的方法,因为有多种方法可以做到这一点,并且关于该主题的 SO 有很多答案。

于 2013-09-15T14:15:15.893 回答