Parsing parameters in Python Cmd module
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 w开发者_JAVA百科ay 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_args
passing 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 call parser.parse_args(args_str.split())
and it will parse correctly the options.
Best option is the argparse module.
I love getopt because it is simple.
How about the shlex module. I think it is exactly for this purpose.
精彩评论