using optparser

Chris Hulan chris.hulan at gmail.com
Sun Oct 17 00:13:16 EDT 2010


On Oct 16, 10:59 pm, jimgardener <jimgarde... at gmail.com> wrote:
> hi
> I have a program which I call  findmatch that expects these arguments
> 1.a person name
> 2.a group name
> 3.an integer
> 4.a float value
>
> I thought I would allow user to call this program either using options
> or using positional arguments in a predefined order
> ie,
> findmatch  -f schoolmates -i jon -t 3.5 -n 115
> or
> findmatch jon schoolmates 115 3.5
>
> I tried to code this using optparser..
>
> def parse_arguments():
>     usage = """usage: %prog [options]
>     eg:
>     findmatch -i jon -f schoolmates   -n 115 -t 3.5
>     """
>     parser = OptionParser(usage)
>
>     parser.add_option('-i','--person',dest='personname',help='person
> to be matched')
>     parser.add_option('-f','-group',dest='groupname', help='group
> containing people to be tested against')
>     parser.add_option('-n','--
> num',dest='samplenumber',type='int',help='how many samples to be used
> ')
>     parser.add_option('-t','--
> cutoff',dest='cutoff',type='float',help='some upperlimit ')
>
>     options,args = parser.parse_args()
>
>     def check_if_person_name_valid(name):
>         if not person_exists(name):
>             parser.error('you must give an valid person name')
>     def check_if_group_name_valid(name):
>         if not group_exists(name):
>             parser.error('you must give a valid group')
>
>     if not options.personname or not options.groupname:
>         print parser.format_help()
>         parser.exit()
>     check_if_person_name_valid(options.personname)
>     check_if_group_name_valid(options.groupname)
>
>     return options
>
> iif __name__=='__main__':
>     options = parse_arguments()
>     person_name = options.personname
>     group = options.groupname
>     number_of_samples_to_use = options.samplenumber
>     cutoff = options.cutoff
>     msg = 'You are trying to match {0} against group {1} using {2}
> samples \
> and using {3:2.2f} as the upper limit '
>     print msg.format(person_name ,  group , number_of_samples_to_use ,
> cutoff )
>
> This can handle keyword arguments.But if I have to allow a user to
> input arguments without options
> ie
> findmatch jon schoolmates 115 3.5
>
> can I do this in the above method? If user enters the above line ,the
> options instance would have
> {  'personname': None ,'groupname': None ...}
> and
> args will contain a list of positional arguments .
>
> I am not sure how this can be processed so that a user is given
> freedom to choose either.
> Any suggestions most welcome.
> regards,
> jim

You could check if args has 4 elements, assuming they are the
positional args just assign them to the options
Or you could check the command line to see if there are any items
starting with '-', and then proceed accordingly.



More information about the Python-list mailing list