optparse: add trailing text in help message?

James Stroud jstroud at mbi.ucla.edu
Fri Oct 13 23:41:31 EDT 2006


Count László de Almásy wrote:
> Is there a standard way with optparse to include a blurb of text after
> the usage section, description, and the list of options?  This is
> often useful to include examples or closing comments when the help
> message is printed out.  Many of the GNU commands do this.
> 
> It would look something like this:
> 
> % program --help
> 
> usage: program [options]
> 
> This is my description text.
> 
> options:
>  -f BAR, --foo=BAR
>                 A sample option
>  --version   show program's version number and exit
>  --help       show this help message and exit
> 
> ==> Now how about closing text after the options list?


Maybe subclass OptionParser?


py> from optparse import OptionParser
py>
py> class OptionParserSpecial(OptionParser):
...   def format_help(self, *args, **kwargs):
...     result = OptionParser.format_help(self, *args, **kwargs)
...     if hasattr(self, 'trailing_text'):
...       return "%s\n%s\n" % (result, self.trailing_text)
...     else:
...        return result
...
py>
py> usage = 'usage: dosomething [options] path'
py> parser = OptionParserSpecial(usage)
py> parser.add_option("-a", "--all", dest="all",
...            action='store_true', default=False,
...            help="don't skip hidden or binary files")
<Option at 0x404f61ac: -a/--all>
py> parser.trailing_text = 'Some extra info here.'
py>
py> options, args = parser.parse_args()
py>
py> parser.print_help()
Usage: dosomething [options] path

Options:
   -h, --help  show this help message and exit
   -a, --all   don't skip hidden or binary files

Some extra info here.


James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list