python optparse,如何在使用输出中包含其他信息?

时间:2021-11-28 23:18:07

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:

使用python的optparse模块我想在常规使用输出下面添加额外的示例行。我当前的help_print()输出如下所示:

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:

我想在我的工作中包含较少* nix识字用户的用法示例。像这样的东西:

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:

我怎么做到这一点? optparse选项允许哪些选项?当前代码:

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 个解决方案

#1


39  

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.

默认的format_epilog剥离换行符(使用textwrap),因此您需要在解析器中覆盖format_epilog,就像这样。

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

这里有更多细节。如果你在类OptionParser中查看optparse.py,有一个名为format_epilog的方法,由format_help调用

here is the snippet from optparse.py

这是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

formatter.format_epilog的默认行为是使用textwrap.fill,其中包括从epilog中删除换行符。由于我们希望保留换行符,因此我们将OptionParser子类化并更改format_epilog的行为

#2


11  

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.

我认为这会覆盖程序中OptionParser类的所有用法的epilog格式,但是,所有这些epilog必须逐字传递,在程序中的其他位置使用OptionParser。

#3


5  

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] 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'

选项:-h, - help显示此帮助消息并退出-v, - verbose产生大量噪音[默认] -q, - 静音(我正在寻找wabbits)-fFILE, - file = FILE写输出到FILE -mMODE, - mode = MODE交互模式:'新手','中间',[默认],'专家'之一

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

危险选项:注意:使用这些选项需要您自担风险。据信其中一些人咬人。 -g组选项。

Have a look here.

看看这里。

#4


4  

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:

关于如何执行此操作的另一个想法是禁用-h的默认行为并打印您自己的帮助屏幕,其中可以包含默认行为:

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.

这基本上是解析器使用add_help_option = True的默认行为执行的操作,当然不包括打印。

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


2  

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.

您可以将一个描述参数传递给OptionParser构造函数。这允许您包括在使用后但在选项列表之前出现的任意文本。

See 16.4.3.1. Creating the parser.

见16.4.3.1。创建解析器。

#6


0  

I subclassed IndentedHelpFormatter, and it was pretty simple:

我将IndentedHelpFormatter子类化,它非常简单:

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 ""

#1


39  

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.

默认的format_epilog剥离换行符(使用textwrap),因此您需要在解析器中覆盖format_epilog,就像这样。

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

这里有更多细节。如果你在类OptionParser中查看optparse.py,有一个名为format_epilog的方法,由format_help调用

here is the snippet from optparse.py

这是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

formatter.format_epilog的默认行为是使用textwrap.fill,其中包括从epilog中删除换行符。由于我们希望保留换行符,因此我们将OptionParser子类化并更改format_epilog的行为

#2


11  

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.

我认为这会覆盖程序中OptionParser类的所有用法的epilog格式,但是,所有这些epilog必须逐字传递,在程序中的其他位置使用OptionParser。

#3


5  

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] 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'

选项:-h, - help显示此帮助消息并退出-v, - verbose产生大量噪音[默认] -q, - 静音(我正在寻找wabbits)-fFILE, - file = FILE写输出到FILE -mMODE, - mode = MODE交互模式:'新手','中间',[默认],'专家'之一

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

危险选项:注意:使用这些选项需要您自担风险。据信其中一些人咬人。 -g组选项。

Have a look here.

看看这里。

#4


4  

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:

关于如何执行此操作的另一个想法是禁用-h的默认行为并打印您自己的帮助屏幕,其中可以包含默认行为:

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.

这基本上是解析器使用add_help_option = True的默认行为执行的操作,当然不包括打印。

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


2  

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.

您可以将一个描述参数传递给OptionParser构造函数。这允许您包括在使用后但在选项列表之前出现的任意文本。

See 16.4.3.1. Creating the parser.

见16.4.3.1。创建解析器。

#6


0  

I subclassed IndentedHelpFormatter, and it was pretty simple:

我将IndentedHelpFormatter子类化,它非常简单:

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 ""