Python : parsing the command line options using optparse

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


>
>
>
> Thanks  Peter  and Simon for the hints  it worked  : )  without ' ='
>
> # Python corrupt.py -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
questions



Question 1 :


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


Example:


Entered at cli #python corrupt.py -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':

        corrupt_inode()

   elif  object_type  == 'DATA':

                corrupt_data()



               OR

if options.object_type == 'LIN':

       corrupt_inode()

   elif  options.object_type  == 'DATA':

         corrupt_data()

   elif  options.object_type  == 'INODE':

         corrupt_data()



#output

#python corrupt.py -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 corrupt.py -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: <http://mail.python.org/pipermail/python-list/attachments/20140301/eb4e7667/attachment.html>


More information about the Python-list mailing list