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

发布于 2024-08-13 06:15:31 字数 1041 浏览 4 评论 0原文

使用 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

我希望它包含工作中 *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

我将如何实现这一目标?哪些 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()

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

忆离笙 2024-08-20 06:15:31
parser = optparse.OptionParser(epilog="otherstuff")

默认的 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
""")
...

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

这是来自 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)

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

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

烛影斜 2024-08-20 06:15:31

详细阐述获胜的答案(这帮助我在自己的代码中解决了同样的问题),一个快速而肮脏的选择是使用标识方法直接覆盖类的方法:

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

将帮助文本打印为逐字结尾。

然而,我认为这会覆盖程序中所有使用 OptionParser 类的 Epilog 格式,因此在程序中其他地方使用 OptionParser 时,所有此类 Epilog 都必须逐字传递。

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.

2024-08-20 06:15:31

使用 usage 参数:

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

您可以通过以下方式添加更多内容(仅作为示例):

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)

示例输出:

用法:[选项] arg1 arg2

选项:-h, --help 显示此帮助消息并退出
-v, --verbose 产生大量噪音 [默认]
-q, --quiet 非常安静(我在猎兔)
-fFILE, --file=FILE 将输出写入 FILE
-mMODE, --mode=MODE 交互模式:“新手”、“中级”、[默认]、“专家”之一

危险选项:警告:使用
这些选项的风险由您自行承担。它
据信其中一些会咬人。
-g 组选项。

看看这里

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.

对不⑦ 2024-08-20 06:15:31

关于如何执行此操作的另一个想法是禁用 -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()

这基本上就是解析器对 -h 的默认行为所做的操作code>add_help_option=True,当然不包括 print

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

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.

将军与妓 2024-08-20 06:15:31

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

请参阅16.4.3.1。创建解析器

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.

忆梦 2024-08-20 06:15:31

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

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 ""
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文