my python version is 2.4.3.
Now I am developing a CLI with cmd module from python for a CD player. I have some classes like CDContainer (with method like addCD, removeCD, etc), CD (with method like play, stop, pause). Now, I want to add some options for the commands and also if the options inputs are not correct, the CLI could return proper information about either wrong input type or wrong values. e.g., I want to have “addcd –track 3 –cdname thriller”. what I am doing now is to get all the arguments via , split it, and assign it to the relevant variables, as follows.
my question is in python, is there some module that is handy for my case to parse and analyse the options or arguments ?
REVISION: OK, I edit it, thanks to gclj5 comments.
import cmd
class CDContainerCLI(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)
cd_obj= CD()
cd_obj.addCD(options.track_number, options.cd_name)
If possible, could you write some code samples, just to show how to do it?
Thank you very much!!
Depending on your Python version, you should take a look at either optparse (since version 2.3, deprecated since version 2.7) or argparse (since version 2.7).
Some sample code using optparse (
lineis the string you read from stdin in your CLI):This parser only handles your “addcd” command. For more commands you could use several
OptionParserobjects in a dictionary with the command name as the key, for instance. You could parse the options like this then:Take a look at the documentation for optparse for more information. It’s very easy to output usage information, for instance. There is also a tutorial available.