tags:

views:

110

answers:

2

Is there any short way to achieve what APT does in Python ?

I mean, when the package manager prompts a yes/no question followed by "[Yes/no]".

The scripts accepts YES/Y/yes/y or "enter" (defaults to Yes as hinted by the capital)

The only thing I find in the official doc is input/raw_input..

I know it's not that hard to emulate, but it's annoying to rewrite :|

+9  A: 

As you mentioned, the easiest way is to use raw_input(). There is no built-in way to do this. From Recipe 577058:

import sys

def query_yes_no(question, default="yes"):
    """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 == "yes":
        prompt = " [Y/n] "
    elif default == "no":
        prompt = " [y/N] "
    else:
        raise ValueError("invalid default answer: '%s'" % default)

    while True:
        sys.stdout.write(question + prompt)
        choice = raw_input().lower()
        if default is not None and choice == '':
            return valid[default]
        elif choice in valid:
            return valid[choice]
        else:
            sys.stdout.write("Please respond with 'yes' or 'no' "\
                             "(or 'y' or 'n').\n")
# Usage example

>>> query_yes_no("Is cabbage yummier than cauliflower?")
Is cabbage yummier than cauliflower? [Y/n] oops
Please respond with 'yes' or 'no' (or 'y' or 'n').
Is cabbage yummier than cauliflower? [Y/n] y
>>> True
fmark
`elif choice in valid:` And I'd probably return a boolean.
Ignacio Vazquez-Abrams
Good choice Ignacio, amending
fmark
+4  A: 

I'd do it this way:

# raw_input returns the empty string for "enter"
yes = set(['yes','y', 'ye', ''])
no = set(['no','n'])

choice = raw_input().lower()
if choice in yes:
   return True
elif choice in no:
   return False
else:
   sys.stdout.write("Please respond with 'yes' or 'no'")
Vicki Laidler