An optparse question

Simon Forman rogue_pedro at yahoo.com
Fri Jul 21 16:46:56 EDT 2006


T wrote:
> fuzzylollipop wrote:
> >
> > you can make the usage line anything you want.
> >
> > ...
> > usage = 'This is a line before the usage line\nusage %prog [options]
> > input_file'
> > parser = OptionsParser(usage=usage)
> > parser.print_help()
> > ...
> >
>
> 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:
>
> % myprog.py -h
> ************ THIS IS NEWLY INSERTED STRING ************
> usage: myprog.py [options] input_file
>
>
> options:
>   -h, --help             show this help message and exit
>   -v, --verbose        print program's version number and exit
>   -o FILE               Output file

It's possible, but it ain't easy:

from optparse import OptionParser, _, IndentedHelpFormatter

class MyFormatter(IndentedHelpFormatter):
    pre_usage = "Hi there!\n"
    def format_usage(self, usage):
        return _("%susage: %s\n") % (self.pre_usage, usage)

parser = OptionParser(formatter=MyFormatter())


The above filthy hack will print "Hi there!" before the usual usage
message.




More information about the Python-list mailing list