Optparse to parsing Suggestions !!

Peter Otten __peter__ at web.de
Fri May 30 11:53:09 EDT 2014


Ganesh Pal wrote:

> Hello Python world ,
> 
> 
> I wanted suggestion on how to modify the below code to help me accomodate
> the below two cases
> 
> # Here is the Sample code.
> 
> def main():
>     """ ---MAIN--- """
>     parser = optparse.OptionParser(usage='%prog [options] <arg1>.]',
> version='1.0')
>    object_choice = ('super_block','blocks''files', 'directory','links')
> 
>   parser.add_option("-o", "--object",
> 
action="store",metavar="object",default='inode',dest="object",type='choice',
> choices=object_choice,
>                      help='The object type to be corrupted [ choose from
>                      ('
> + ','.join(object_choice) + ') default: %default]',)
> 
>     parser.add_option("-p",
> "--
path",action="store",metavar="/mnt/",dest="path",type="string",help="The
> file or directory path in /mnt/",)
> 
>     parser.add_option("-n",
> "--
size",action="store",metavar="size",dest="size",default=1,type='int',help="The
> offset field)
> 
> 
> # Instruct optparse to parse the program's command line:
>   (options, args) = parser.parse_args()
> 
>     # Build the dispatch table:
>     object_type_dictionary = {
>          "super_block":super_block_def,
>          "blocks":blocks_def,
>         "files": files_corrupt_def,
>         "directory": directory_corrupt_def,
>        "links": links_corrput_def, # no () here,we're storing function
>     }
> 
>     # Lookup the object type and then call the function:
>     object_type_dictionary[options.object]()
> 
> 
> Sample Run
> # python corrupt.py  --object=files --path=/tmp/ --size 1000
> 
> 
> Questions :
> 
> Case 1:  #  The  --path is optional for few for the object type.  How do I
> simulate the below behaviour
> 
>          #python corrupt.py  --object=super_block  --size=1000
> 
>           ==>  Should work even if --path is not given
> 
>          #python corrupt.py  --object=super_block  --path=/tmp/--size 1000
> 
>         ==>  If user enters --object=super_block and --path=/ifs/ should
> throw an error
> 
>    saying its an invaild combinations.
> 
> 
> 
> case 2:  # The --path is mandatory for few of the object types and  should
> complain if its not entered .
> 
>           # python corrupt.py  --object=files --path=/tmp/ --size 1000

I think you have to do it manually:

options, args = parser.parse_args()

if options.object == "super_block" and options.path is not None:
    parser.error("Paths not allowed for 'super_block' object")
elif options.object == "files" and options.path is None:
    parser.error("'files' object requires a path")





More information about the Python-list mailing list