Using python's optparse module I would like to add extra example lines below the regular usage output. My current help_print() output looks like this:
usage: check_dell.py [options]
options:
-h, --help show this help message and exit
-s, --storage checks virtual and physical disks
-c, --chassis checks specified chassis components
I would like it to include usage examples for the less *nix literate users at my work. Something like this:
usage: check_dell.py [options]
options:
-h, --help show this help message and exit
-s, --storage checks virtual and physical disks
-c, --chassis checks specified chassis components
Examples:
check_dell -c all
check_dell -c fans memory voltage
check_dell -s
How would I accomplish this? What optparse options allow for such? Current code:
import optparse
def main():
parser = optparse.OptionParser()
parser.add_option('-s', '--storage', action='store_true', default=False, help='checks virtual and physical disks')
parser.add_option('-c', '--chassis', action='store_true', default=False, help='checks specified chassis components')
(opts, args) = parser.parse_args()
The default
format_epilog
strips the newlines (uses textwrap), so you would need to overrideformat_epilog
in your parser like this.Here's a bit more detail.
If you look in
optparse.py
in the classOptionParser
there is a method calledformat_epilog
which is called byformat_help
here is the snippet from optparse.py
The default behaviour of
formatter.format_epilog
is to usetextwrap.fill
which amongst other things, strips the newlines from the epilog. Since we want the newlines to be preserved, we subclassOptionParser
and change the behaviour offormat_epilog
There is a
description
parameter you can pass to theOptionParser
constructor. This allows you to include arbitrary text that appears afterusage
, but before the list of options.See 16.4.3.1. Creating the parser.
Another idea on how to do this would be disabling the default behavior for
-h
and printing your own help screen, which can include the default one:That is basically what the parser does with the default behavior of
add_help_option=True
, excluding of course theprint
s.But, in all honesty, I'd also prefer a way to simply add any given number of description lines in the beginning and in the end.
I subclassed IndentedHelpFormatter, and it was pretty simple:
Use the
usage
parameter:You can add more through (just an example):
Example output:
Have a look here.
Elaborating on the winning answer (which helped me solve the same problem in my own code), one quick-and-dirty option is to directly override the class's method with an identity method:
to get helptext printed as a verbatim epilog.
I think this overrides the epilog formatting for all uses of the OptionParser class in your program, however, so all such epilogs must be passed in verbatim where you use OptionParser elsewhere in your program.