An optparse question

Simon Forman rogue_pedro at yahoo.com
Fri Jul 21 17:01:18 EDT 2006


dan.g... at gmail.com wrote:
> > No, that affects the string printed only *after* the "usage = " string.
> >  What I would like to do is insert some string *before* the "usage = "
> > string, which is right after the command I type at the command prompt.
> > So I would like to make it look like this:
>
> The example was fine (except for a typo) as far as demonstrating the
> concept.  Try this corrected version:
>
> from optparse import OptionParser
>
> usage = '************ THIS IS NEWLY INSERTED STRING
> ************\nusage: %prog [options] input_file'
> parser = OptionParser(usage=usage)
> parser.print_help()

Nope.  That only *nearly* does what T wants.  The usage message will
still be printed immediately *after* the 'usage: ' string.

>>> parser = OptionParser(usage=usage)
>>> parser.print_help()
usage: ************ THIS IS NEWLY INSERTED STRING************
usage: lopts.py [options] input_file

options:
  -h, --help  show this help message and exit


I had the same problem, and in order to get something printed before
the usage message, I found one easy-ish way was to subclass the
Formatter passed in to the Parser.

IMHO, optparse does a tricky task well, but it's implemented in a hard
to follow, inflexible manner.  My "favorite" pet peeve is that the
options "dictionary" it returns isn't a dict.  I wound up doing this to
it to get something [I considered] useful:

    o, a = parser.parse_args()
    o = o.__dict__.copy()


Peace,
~Simon




More information about the Python-list mailing list