Python : parsing the command line options using optparse

Ganesh Pal ganesh1pal at
Sat Mar 1 12:13:11 CET 2014

> Thanks  Peter  and Simon for the hints  it worked  : )  without ' ='
> # Python -o INODE -p /ifs/1.txt -q SET -f 1
> Current Default Choice :
> Choice: INODE
> Choice: SET
> Choice: 1

Iam done with the command line parsing but got stuck while trying to
implement switch kind of behavior with dictionaries.  So posting 2 more

Question 1 :

Iam using the  directly  for manipulations is this fine or do
I need to assign it to variable and then use it


Entered at cli #python -object_type INODE  --path_name/ifs/1.txt
-operation_type SET

Initialize all the command line option and then use it

object_type = options.object_type

path_name  = options.path_name

if object_type == 'LIN':


   elif  object_type  == 'DATA':



if options.object_type == 'LIN':


   elif  options.object_type  == 'DATA':


   elif  options.object_type  == 'INODE':



#python -object_type INODE  -p /ifs/1.txt -q SET -f 10

 -m 10  -n 123  -l  -c

Corrupted inode


Question 2 :

I wanted to use dictionary to match the above if else behavior (we don't
have switch in python I guess ) and  If else looks very untidy.

Is it possible to store the options.object_type as a key in the dictionary
and   then based on the value entered in the command line invoke the
appropriate function

I tried creating a dictionary like this but Iam getting a wrong output

object_type_dictonary = { 'LIN' : corrupt_inode(),

                                      'INODE' : corrupt_lin(),

                                         'DATA' : corrupt_data(),


and then  ran # python -object_type= inode  (  This prints all
the values for me)

Example :

Corrupted inode

Corrupted LIN

Corrupted  data

PS : If user enters object_type= inode it should execute  corrupt_inode
  and print corrupted inode

Any help on  tips highly helpful :)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list