Statistics
| Branch: | Tag: | Revision:

root / devflow / ui.py @ 2e9bddbf

History | View | Annotate | Download (1.5 kB)

1
#!/usr/bin/env python
2

    
3
import sys
4

    
5
#http://stackoverflow.com/questions/3041986/python-command-line-yes-no-input
6
def query_yes_no(question, default="yes"):
7
    """Ask a yes/no question via raw_input() and return their answer.
8

9
    "question" is a string that is presented to the user.
10
    "default" is the presumed answer if the user just hits <Enter>.
11
        It must be "yes" (the default), "no" or None (meaning
12
        an answer is required of the user).
13

14
    The "answer" return value is one of "yes" or "no".
15
    """
16
    valid = {"yes":True,   "y":True,  "ye":True,
17
             "no":False,     "n":False}
18
    if default == None:
19
        prompt = " [y/n] "
20
    elif default == "yes":
21
        prompt = " [Y/n] "
22
    elif default == "no":
23
        prompt = " [y/N] "
24
    else:
25
        raise ValueError("invalid default answer: '%s'" % default)
26

    
27
    while True:
28
        sys.stdout.write(question + prompt)
29
        choice = raw_input().lower()
30
        if default is not None and choice == '':
31
            return valid[default]
32
        elif choice in valid:
33
            return valid[choice]
34
        else:
35
            sys.stdout.write("Please respond with 'yes' or 'no' "\
36
                             "(or 'y' or 'n').\n")
37

    
38
def query_action(question, default="yes", action=None):
39
    answer = query_yes_no(question, default)
40
    if answer and action is not None:
41
        action()
42

    
43
def query_user(question, default=""):
44
    prompt = "[" + default + "]"
45
    sys.stdout.write(question + prompt)
46
    answer = raw_input()
47
    if answer == "":
48
        return default
49
    return answer