Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing parameters in Python Cmd module

Tags:

python

cmd

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.

like image 831
Mr_Chimp Avatar asked Sep 02 '26 07:09

Mr_Chimp


2 Answers

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.

like image 156
maid450 Avatar answered Sep 03 '26 22:09

maid450


Best option is the argparse module.

like image 36
joksnet Avatar answered Sep 03 '26 21:09

joksnet