Source code for mmf.utils.input

"""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 input(varname="input",dtype=None,default=None,eval=None, raw_input=raw_input): """Prompts the user to input a variable. The user can break out of the input with ctrl-c upon which a Cancel exception is raised. Return dtype(eval(raw_input(message))) where the message includes the variable name and defualt value (if provided). Note that using eval is dangerous as it allows the user to execute arbitrary code. A safe version of eval should be provided if security is a concern. If default is defined but dtype is not, then dtype = type(default). >>> input("c",dtype=float,eval=eval,raw_input=simulate_input("5.5+2.0")) c = : 5.5+2.0 7.5 >>> input("c",default=2.5,raw_input=simulate_input("")) c = (2.5): 2.5 >>> try: input("c",raw_input=simulate_input("")) ... except Invalid, err: print str(err) + " (No default)" c = : Invalid Input. (No default) >>> try:input("c",default=1.0,raw_input=simulate_input("abc")) ... except Cancel, err: print "Cancelled: " + str(err) c = (1.0): abc Cancelled: Invalid Input. >>> try: input("c",raw_input=simulate_cancel) ... except Cancel, err: print "Cancelled: " + str(err) c = : ^C Cancelled: Cancelled. """ def noop(x): """Do nothing.""" return x if default is not None: mesg = varname + " = (" + `default` + "): " else: mesg = varname + " = : " if dtype is None: if default is not None: # If default is specified, use it to dtype = type(default) # define filter type else: dtype = noop if eval is None: eval = noop try: inp = raw_input(mesg) except: raise Cancel if 0 == len(inp): if default is None: raise Invalid else: inp = `default` try: v = dtype(eval(inp)) except: raise Invalid return v
[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