"""Input processing functions for simplifying input from the user.
These allow the user to enter a value or quit with ctrl-c and throw a
Cancel exception."""
__all__ = ['Cancel','Invalid','input','okay']
from mmf.utils.mmf_test import simulate_input, simulate_cancel
[docs]class Cancel(Exception):
"""Exception raised by input routines to signify that the user has
cancelled the entry via ctrl-c rather than entered a value.
>>> try:
... raise Cancel
... except Cancel, c:
... print "Caught Exception: " + str(c)
Caught Exception: Cancelled.
"""
[docs] def __init__(self,mesg="Cancelled."):
Exception.__init__(self,mesg)
[docs]class Invalid(Cancel):
"""Exception raised by input routines to signify that the user has
entered and invalid input. This is a subclass of Cancel so that
an invalud input can be used to cancel the input, but
specializations can be made.
>>> try:
... raise Invalid
... except Invalid, c:
... print "Caught Exception: " + str(c)
Caught Exception: Invalid Input.
"""
[docs] def __init__(self,mesg="Invalid Input."):
Exception.__init__(self,mesg)
[docs]def okay(message="yes or no?",default=None,raw_input=raw_input):
"""Return True if the user responds with an affirmative, False
otherwise, or throw a Cancel exception. A default may be
provided.
>>> okay(raw_input=simulate_input("yes"))
yes or no? yes
True
>>> okay(message="okay?",raw_input=simulate_input("n"))
okay? n
False
>>> okay(default="yes",raw_input=simulate_input(""))
yes or no? (yes):
True
>>> okay(default="yes",raw_input=simulate_input(["blah","okay"]))
yes or no? (yes): blah
Invalid Response: Please answer "yes" or "no".
yes or no? (yes): okay
True
>>> try:okay(raw_input=simulate_cancel)
... except Cancel, err: print "Cancelled: " + str(err)
yes or no? ^C
Cancelled: Cancelled.
"""
NotDone = True;
if default is not None:
mesg = message + " (" + default + "): "
else:
mesg = message + " "
while NotDone:
try:
inp = raw_input(mesg)
except:
raise Cancel
if 0 == len(inp):
inp = default
inp = str.lower(inp)
yes = map(str.lower,["yes","true","ok","okay","alright","y"])
no = map(str.lower,["no","false","not","never","n"])
if 0 < yes.count(inp):
NotDone = False
ans = True
elif 0 < no.count(inp):
NotDone = False
ans = False
else:
print ('Invalid Response: Please answer "yes" or "no".')
return ans