question.py
From Club Ubuntu
This code is meant as a way to help with user input from the CLI
Code
""" A questionaire for things like installers, wizards, etc """
import re
class question:
def __init__(self, question, match="", invalid_statement="'{{input}}' is not valid"):
""" question asks a question ("question") and will only continue if
the input received matches the regex "match". If match is empty
then it is assumed anything matches. invalid_statement is printed when
the user inputs something not matching matches. An optional {{input}}
var can be used in the invalid_statement argument.
"""
self.question = question
self.match_value = match
self.match = re.compile(match.lower())
self.invalid_statement = invalid_statement
question_complete = False
while not question_complete:
self._input = raw_input(self.question)
# First makes sure that question wants a specific value and if so,
# checks for this value. Otherwise, the question is complete.
if self.match_value and not self.match.match(self._input.lower()):
print self.invalid_statement.replace("{{input}}", self._input)
else:
question_complete = True
def ask(self):
self.__init__(self.question, self.match_value, self.invalid_statement)
def get_result(self):
return self._input
def get_match(self):
return self.match.match(self._input.lower())

