python optparse, how to include additional info in

2019-03-09 17:48发布

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

6条回答
Rolldiameter
2楼-- · 2019-03-09 18:33
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

查看更多
等我变得足够好
3楼-- · 2019-03-09 18:42

There is a description parameter you can pass to the OptionParser constructor. This allows you to include arbitrary text that appears after usage, but before the list of options.

See 16.4.3.1. Creating the parser.

查看更多
干净又极端
4楼-- · 2019-03-09 18:44

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:

from optparse import OptionParser

parser = OptionParser(add_help_option=False, 
                      epilog="This can't be easily\n multilined")
parser.add_option('-h', '--help', dest='help', action='store_true',
                  help='show this help message and exit')

(options, args) = parser.parse_args()

if options.help:
    parser.print_help()
    print 'now we have an epilog'
    print 'with as many lines as you wish'
    sys.exit()

That is basically what the parser does with the default behavior of add_help_option=True, excluding of course the prints.

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.

查看更多
手持菜刀,她持情操
5楼-- · 2019-03-09 18:48

I subclassed IndentedHelpFormatter, and it was pretty simple:

class PlainHelpFormatter(optparse.IndentedHelpFormatter):
    def format_description(self, description):
        if description:
            return description + "\n"
        else:
            return ""
    def format_epilog(self, epilog):
        if epilog:
            return epilog + "\n"
        else:
            return ""
查看更多
Luminary・发光体
6楼-- · 2019-03-09 18:49

Use the usage parameter:

usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)

You can add more through (just an example):

group = OptionGroup(parser, "Dangerous Options",
                    "Caution: use these options at your own risk.  "
                    "It is believed that some of them bite.")
group.add_option("-g", action="store_true", help="Group option.")
parser.add_option_group(group)

Example output:

usage: [options] arg1 arg2

options: -h, --help show this help message and exit
-v, --verbose make lots of noise [default]
-q, --quiet be vewwy quiet (I'm hunting wabbits)
-fFILE, --file=FILE write output to FILE
-mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate', [default], 'expert'

Dangerous Options: Caution: use of these options is at your own risk. It is believed that some of them bite. -g Group option.

Have a look here.

查看更多
Evening l夕情丶
7楼-- · 2019-03-09 18:53

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:

optparse.OptionParser.format_epilog = lambda self, formatter: self.epilog
optparser = optparse.OptionParser(epilog=helptext)

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.

查看更多
登录 后发表回答