optparse question

George Yoshida ml at dynkin.com
Sat Sep 18 17:15:35 EDT 2004


GMTaglia wrote:
> Hi guys,
> 
> I was wondering why optparse accept an option if in the command line is not
> *exactly* the one present in the source code....may be an example will
> explain better....
> 
> #!/usr/bin/env python
> 
> import optparse as opt
> 
> parser = opt.OptionParser()
> parser.add_option("-f", "--filein", dest="fileinput", help="filename to
> read", metavar="FILE")
> (options, args) = parser.parse_args()
> count = 0
> filename = open(options.fileinput, 'r')
> for lines in filename.xreadlines():
>     count += 1
> print count
> 
> if you run this dumb example in this way:
> 
> liquid at jupiter liquid $ ./testi.py --fil elenco_tm.txt
> 367
> 
> it goes on, but the option must be --filein not --fil
> 
> Is true that if you have another option like 
> 
> parser.add_option("-f", "--fileout", dest="fileoutput", help="filename to
> write", metavar="FILE")
> 
> the program will stop raising a conflict option, but why accept only the
> beginning of the long option instead of the exact one?

I encountered the same question, looked at the source and found 
the answer.

Quote from the document of getopt module:
   http://docs.python.org/lib/module-getopt.html

   Long options on the command line can be recognized so long as they
   provide a prefix of the option name that matches exactly one of
   the accepted options. For example, it long_options is ['foo',
   'frob'], the option --fo will match as --foo, but --f will not
   match uniquely, so GetoptError will be raised.

optparse is same as getopt in this respect.

George



More information about the Python-list mailing list