I am writing a command line tool in Python using the Cmd module.
I want to be able to issue commands such as:
resize -file all -height 100 -width 200 -type jpeg
or
resize -file 'a file.jpg' -type png -height 50 -width 50
[edit] To be clear the above command is to be enter into my command line application NOT from the terminal. The line above would call the do_resize(self, line) method of my Cmd module and pass in the parameters as a string. For this reason OptParse and argparse don’t do what I need as they appear to only get paramters from sys.argv.
Some parameters are required, some are optional. Some become required when others are used.
What is the best way to parse the parameter string? I have read there are tools in Python that make this easy but I’m not sure what I’m look for.
you are looking for optparse (argparse for python 2.7+)
edit: In fact according to this section of docs, you can call function
parse_argspassing a list of arguments, which defults (but not limits to)sys.argv[1:]So, if you have for example
args_str = '-file all -height 100 -width 200 -type jpeg'you can callparser.parse_args(args_str.split())and it will parse correctly the options.