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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1857346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:13:29  来源:igfitidea点击:

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

pythonoptparse

提问by CarpeNoctem

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

回答by John La Rooy

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

The default format_epilogstrips the newlines (uses textwrap), so you would need to override format_epilogin 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.pyin the class OptionParserthere is a method called format_epilogwhich is called by format_help

这里有更多细节。
如果你在optparse.py类中查看OptionParser有一个调用的方法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_epilogis to use textwrap.fillwhich amongst other things, strips the newlines from the epilog. Since we want the newlines to be preserved, we subclass OptionParserand change the behaviour of format_epilog

的默认行为formatter.format_epilog是使用textwrap.fillwhich,除其他外,从结语中删除换行符。由于我们希望保留换行符,因此我们子类化OptionParser并更改了format_epilog

回答by user117529

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 类的所有使用的结语格式,因此所有这些结语必须逐字传递,您在程序中的其他地方使用 OptionParser。

回答by jldupont

Use the usageparameter:

使用usage参数:

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.

用法:[选项] arg1 arg2

选项:-h, --help 显示此帮助信息并退出
-v, --verbose 制造大量噪音 [默认]
-q, --quiet 保持安静(我正在寻找 wabbits)
-fFILE, --file= FILE 将输出写入 FILE
-mMODE, --mode=MODE 交互模式:'新手'、'中级'、[默认]、'专家'之一

危险选项:注意:使用这些选项的风险由您自己承担。据信,其中一些会咬人。-g 组选项。

Have a look here.

看看这里

回答by cregox

Another idea on how to do this would be disabling the default behavior for -hand 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,当然不包括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.

但是,老实说,我也更喜欢一种在开头和结尾简单地添加任意给定数量的描述行的方法。

回答by Yang Zhao

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

有一个description参数可以传递给OptionParser构造函数。这允许您包含出现在 之后usage但在选项列表之前的任意文本。

See 16.4.3.1. Creating the parser.

16.4.3.1。创建解析器

回答by user3498817

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