Python : parsing the command line options using optparse

Peter Otten __peter__ at
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 --path=/ifs/1.txt --operation=XOR  --node=11 --log
> -fixcrc
>>>  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
> line)
>        /ifs/1.txt
>  I wanted to store all the options in a list like
> [/ifs/1.txt,XOR,11,log_file,fix_crc]
>  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.

> Question(2)

> 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 ?
> # -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
>  a
> 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",
> default='SET',
>                   type='choice', choices=['XOR', 'ADD', 'SET'
>                   help = "The corruption operation on the object [default
>                   :
> %default]",)

You can move the choices into the help. Example using argparse :

    "-q", "--operation",
    choices=['XOR', 'ADD', 'SET'],
    help="The corruption operation on the object [choose from %(choices)s; 
default: %(default)s]")

This becomes

  -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 mailing list