Search code examples
pythonoptparse

python optparse, how to include additional info in usage output?


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()

Solution

  • parser = optparse.OptionParser(epilog="otherstuff")
    

    The default format_epilog strips the newlines (uses textwrap), so you would need to override format_epilog in your parser like this.

    def main():
    
        class MyParser(optparse.OptionParser):
            def format_epilog(self, formatter):
                return self.epilog
    
        parser =MyParser(epilog=
    """Examples:
    
    check_dell -c all
    check_dell -c fans memory voltage
    check_dell -s
    """)
    ...
    

    Here's a bit more detail.
    If you look in optparse.py in the class OptionParser there is a method called format_epilog which is called by format_help

    here is the snippet from optparse.py

    def format_epilog(self, formatter):
        return formatter.format_epilog(self.epilog)
    
    def format_help(self, formatter=None):
        if formatter is None:
            formatter = self.formatter
        result = []
        if self.usage:
            result.append(self.get_usage() + "\n")
        if self.description:
            result.append(self.format_description(formatter) + "\n")
        result.append(self.format_option_help(formatter))
        result.append(self.format_epilog(formatter))
        return "".join(result)
    

    The default behaviour of formatter.format_epilog is to use textwrap.fill which amongst other things, strips the newlines from the epilog. Since we want the newlines to be preserved, we subclass OptionParser and change the behaviour of format_epilog