Python : parsing the command line options using optparse
__peter__ at web.de
Tue Feb 25 17:25:18 CET 2014
Ganesh Pal wrote:
> Iam newbie to Python, Iam trying to use optparse module and write a script
> that will parse the command line options ..I had to use opt parse instead
> of argparse because by host Operating system is still using python 2.6
As you are just starting I recommend that you use argparse instead of
> Questions (1)
> #python python-5.py --path=/ifs/1.txt --operation=XOR --node=11 --log
>>> Looks like the dest variable stores it in a dictionary ,
It's an instance of optparse.Values.
> >> print options.path_name ( gives the option entered in the command
> I wanted to store all the options in a list like
> please suggest on the same ?
While you can create such a list with
[getattr(options, name) for name in ["path_name", "operation_type", ...]]
I don't see what the advantage over the default format would be. In fact you
are making it harder to access a specific option that way.
> Why does this program work only with - option and not - in the above
> code ?
> I think its not working when the type= 'choice' or its somethimf else ?
> # python-5.py -p=/ifs/1.txt -q=XOR -f=1234 -n=1 -l
If you are asking why short options don't work in conjunction with = -- I
don't know, it is probably a design choice of the optparse author.
argparse accepts short options with like -f=1234
> Question (3)
> If I have really long metavar and the help looks very messy ,is there
> way to make it look elegant.
> Example :
> parser.add_option("-q", "--operation", action="store",
> metavar="XOR|ADD|SET|MODIFY|RENAME|DELETE|KILL|", dest="operation_type",
> type='choice', choices=['XOR', 'ADD', 'SET'
> help = "The corruption operation on the object [default
You can move the choices into the help. Example using argparse :
choices=['XOR', 'ADD', 'SET'],
help="The corruption operation on the object [choose from %(choices)s;
-q OP, --operation OP
The corruption operation on the object [choose from
XOR, ADD, SET; default: SET]
in the help.
More information about the Python-list