HI, guys.
I am using cmd and optparse to develop a CLI.py for a collection of already-functional classes (CDContainer, CD, etc.). The following are some parts of the code. I have a problem here. when there are exceptions(wrong input type or missing values), the optparse will exit the whole program instead of the specific command method.
import cmd
class CLI(cmd.Cmd):
def do_addcd(self, line):
args=line.split()
parser = OptionParser()
parser.add_option("-t", "--track", dest="track_number", type="int",
help="track number")
parser.add_option("-n", "--cdname", dest="cd_name", type="string",
help="CD name")
(options, positional_args) = parser.parse_args(args[0:])
cd_obj= CD()
cd_obj.addCD(options.track_number, options.cd_name)
Under “>python”, if I type CLI.py,
then I will have (Cmd), so I could type command like “(Cmd)addcd -t 3 -n thriller”.
but if I type “addcd -t r -n 3”, then optparse will terminate the whole CLI.py and exit.
This is not good for me. I want to remind the user for each method, instead of terminating the whole program.
however, the optparse documentation says “the whole program exits”. so I could not use optparse “blindly”. what can I do?
The
optparsedocumentation says this:Ideally you’d define a new type of exception, subclass
optparse, raise the exception in theexit()orerror()method that you’ve overridden, and then catch it and deal with it as needed.You can cheat, though. If you want the error message printed but just don’t want the program to exit, then you can catch the
SystemExitexception to catch whereoptparseis trying to exit and stop it.So, for example:
or to override the method:
and then: