I am developing cli with python version 2.4.3. i want to have the input exception check. The following is part of the code. With this code, I can type
addcd -t 11
and if I type
addcd -t str_not_int
or
addcd -s 3
I will catch the error of wrong type argument and wrong option. However, it is not sufficient. e.g.
addcd s 11
or
addcd s a
then the optparse cannot detect this kind of misinput.
to eliminate the case like "addcd s a 11 21", I add something by checking number of argument, but I do not know if it is the right way.
So, how can I implement a thorough/efficient input check for CLI?
class OptionParsingError(RuntimeError):
def __init__(self, msg):
self.msg = msg
class OptionParsingExit(Exception):
def __init__(self, status, msg):
self.msg = msg
self.status = status
class ModifiedOptionParser(optparse.OptionParser):
def error(self, msg):
raise OptionParsingError(msg)
def exit(self, status=0, msg=None):
raise OptionParsingExit(status, msg)
class CDContainerCLI(cmd.Cmd):
"""Simple CLI """
def __init__(self):
""" initialization """
cmd.Cmd.__init__(self)
self.cdcontainer=None
def addcd(self, s):
args=s.split()
try:
parser = ModifiedOptionParser()
parser.add_option("-t", "--track", dest="track_number", type="int",
help="track number")
(options, positional_args) = parser.parse_args(args)
except OptionParsingError, e:
print 'There was a parsing error: %s' % e.msg
return
except OptionParsingExit, e:
print 'The option parser exited with message %s and result code %s' % (e.msg, e.status)
return
if len(args) != 4:
print "wrong number of inputs"
return
cd_obj= CD()
cd_obj.addCD(options.track_number, options.cd_name)