Module to read input from commandline

james at james at
Sun Apr 13 22:05:54 CEST 2008

On Apr 13, 7:44 pm, thashoo... at wrote:
> What you're looking for is no module, it is included in the standard
> python namespace.
> raw_input
> Use it like this:
> value_a = raw_input("Please give a value for a: ")
> # do your thing to value_a
> But this belongs to the real basics, I suggest you get some reading
> done on python.
> GL

Thanks for the response GL.

What I am looking for is a module to wrap raw_input so it can handle
some of the validation.

response = display_prompt( question, valid_responses,
default_response )

or similar.  valid_responses could be a tuple of regexp strings that
would compare against a raw_input and return one in the list.  Ideally
I could customize the error message (for responses not in
valid_response), etc.

I know it isn't rocket science to write it and I have something
already in place.  I'd rather use a module built for the purpose now
that I have several scripts that will use the functionality.


FYI: This is what I have so far:

from re import compile

def yes_no(question, default=None):
    """Prompt the user with a yes or no question."""
    if default == "y":
        question = "".join((question, " [Y/n]: "))
    elif default == "n":
        question = "".join((question, " [y/N]: "))
        question = "".join((question, " [y/n]: "))

    valid_answer = "[yn]"
    invalid_message = "Answer must be y or n"
    answer = prompt(question, valid_answer, invalid_message, default)
    return answer == 'y'

def prompt(question, valid_answer, invalid_message, default=None):
    """Prompt the user with a question and validate their response."""
    is_valid = False;
    compiled_valid_answers = compile(valid_answer)
    while not is_valid:
        answer = raw_input(question).lower()
        if answer == "" and default is not None:
            answer = default
        is_valid = compiled_valid_answers.match(answer)
        if not is_valid:
            print invalid_message
    return answer

More information about the Python-list mailing list