如何使用Python的optparse格式化位置参数帮助?

时间:2022-10-12 23:22:07

As mentioned in the docs the optparse.OptionParser uses an IndentedHelpFormatter to output the formatted option help, for which which I found some API documentation.

正如文档中所提到的,optparse.OptionParser使用IndentedHelpFormatter来输出格式化的选项帮助,为此我找到了一些API文档。

I want to display a similarly formatted help text for the required, positional arguments in the usage text. Is there an adapter or a simple usage pattern that can be used for similar positional argument formatting?

我想在使用文本中显示所需的位置参数的类似格式的帮助文本。是否有适配器或简单的使用模式可用于类似的位置参数格式化?

Clarification

Preferably only using the stdlib. Optparse does great except for this one formatting nuance, which I feel like we should be able to fix without importing whole other packages. :-)

优选仅使用stdlib。 Optparse确实很棒,除了这个格式细微差别,我觉得我们应该能够在不导入其他整个软件包的情况下修复。 :-)

4 个解决方案

#1


19  

The best bet would be to write a patch to the optparse module. In the meantime, you can accomplish this with a slightly modified OptionParser class. This isn't perfect, but it'll get what you want done.

最好的办法是给optparse模块写一个补丁。与此同时,您可以使用略微修改的OptionParser类来完成此操作。这不是完美的,但它会得到你想要的东西。

#!/usr/bin/env python
from optparse import OptionParser, Option, IndentedHelpFormatter

class PosOptionParser(OptionParser):
    def format_help(self, formatter=None):
        class Positional(object):
            def __init__(self, args):
                self.option_groups = []
                self.option_list = args

        positional = Positional(self.positional)
        formatter = IndentedHelpFormatter()
        formatter.store_option_strings(positional)
        output = ['\n', formatter.format_heading("Positional Arguments")]
        formatter.indent()
        pos_help = [formatter.format_option(opt) for opt in self.positional]
        pos_help = [line.replace('--','') for line in pos_help]
        output += pos_help
        return OptionParser.format_help(self, formatter) + ''.join(output)

    def add_positional_argument(self, option):
        try:
            args = self.positional
        except AttributeError:
            args = []
        args.append(option)
        self.positional = args

    def set_out(self, out):
        self.out = out
def main():
    usage = "usage: %prog [options] bar baz"
    parser = PosOptionParser(usage)
    parser.add_option('-f', '--foo', dest='foo',
                      help='Enable foo')
    parser.add_positional_argument(Option('--bar', action='store_true',
                                   help='The bar positional argument'))
    parser.add_positional_argument(Option('--baz', action='store_true',
                                   help='The baz positional argument'))
    (options, args) = parser.parse_args()
    if len(args) != 2:
        parser.error("incorrect number of arguments")
    pass

if __name__ == '__main__':
    main()

And the output you get from running this:

你运行这个输出得到的输出:

Usage: test.py [options] bar baz

  Options:
    -h, --help         show this help message and exit
    -f FOO, --foo=FOO  Enable foo

Positional Arguments:
  bar  The bar positional argument
  baz  The baz positional argument

#2


8  

Try taking a look at argparse. Documentation says it supports position arguments and nicer looking help messages.

试试看argparse。文档说它支持位置参数和更好看的帮助消息。

#3


1  

I'd be interested in a clean solution to this; I wasn't able to come up with one. The OptionParser really focuses entirely on the options; it doesn't give you anything to work with position args, as far as I've been able to find.

我对这个干净的解决方案感兴趣;我无法想出一个。 OptionParser完全专注于选项;据我所知,它并没有给你任何与位置算法有关的东西。

What I did was to generate a list of little documentation blocks for each of my positional arguments, using \ts to get the right spacing. Then I joined them with newlines, and appended that to the 'usage' string that gets passed to the OptionParser.

我所做的是为每个位置参数生成一个小文档块列表,使用\ ts来获得正确的间距。然后我用newlines加入它们,并将其附加到传递给OptionParser的'usage'字符串。

It looks fine, but it feels silly, and of course that documentation ends up appearing above the list of options. I haven't found any way around that, or how to do any complex stuff, i.e. a given set of options is described beneath the description for a positional arg, because they only apply to that arg.

它看起来很好,但感觉很愚蠢,当然文档最终出现在选项列表之上。我没有找到任何方法,或者如何做任何复杂的事情,即在位置arg的描述下面描述了一组给定的选项,因为它们只适用于那个arg。

I looked at monkey-patching OptionParser's methods and I remember (this was a year or so ago) that it wouldn't have been that difficult, but I didn't want to go down that path.

我看了一下猴子修补OptionParser的方法,我记得(这是大约一年前),它不会那么困难,但我不想走那条路。

#4


0  

Most help text for positional arguments resembles the format frequently used in man pages for *NIX boxes. Take a look at how the 'cp' command is documented. Your help text should resemble that.

位置参数的大多数帮助文本类似于* NIX框的手册页中经常使用的格式。看看如何记录'cp'命令。您的帮助文本应该类似于此。

Otherwise as long as you fill out the "help" argument while using the parser, the documentation should produce itself.

否则,只要您在使用解析器时填写“帮助”参数,文档就应该自行生成。

#1


19  

The best bet would be to write a patch to the optparse module. In the meantime, you can accomplish this with a slightly modified OptionParser class. This isn't perfect, but it'll get what you want done.

最好的办法是给optparse模块写一个补丁。与此同时,您可以使用略微修改的OptionParser类来完成此操作。这不是完美的,但它会得到你想要的东西。

#!/usr/bin/env python
from optparse import OptionParser, Option, IndentedHelpFormatter

class PosOptionParser(OptionParser):
    def format_help(self, formatter=None):
        class Positional(object):
            def __init__(self, args):
                self.option_groups = []
                self.option_list = args

        positional = Positional(self.positional)
        formatter = IndentedHelpFormatter()
        formatter.store_option_strings(positional)
        output = ['\n', formatter.format_heading("Positional Arguments")]
        formatter.indent()
        pos_help = [formatter.format_option(opt) for opt in self.positional]
        pos_help = [line.replace('--','') for line in pos_help]
        output += pos_help
        return OptionParser.format_help(self, formatter) + ''.join(output)

    def add_positional_argument(self, option):
        try:
            args = self.positional
        except AttributeError:
            args = []
        args.append(option)
        self.positional = args

    def set_out(self, out):
        self.out = out
def main():
    usage = "usage: %prog [options] bar baz"
    parser = PosOptionParser(usage)
    parser.add_option('-f', '--foo', dest='foo',
                      help='Enable foo')
    parser.add_positional_argument(Option('--bar', action='store_true',
                                   help='The bar positional argument'))
    parser.add_positional_argument(Option('--baz', action='store_true',
                                   help='The baz positional argument'))
    (options, args) = parser.parse_args()
    if len(args) != 2:
        parser.error("incorrect number of arguments")
    pass

if __name__ == '__main__':
    main()

And the output you get from running this:

你运行这个输出得到的输出:

Usage: test.py [options] bar baz

  Options:
    -h, --help         show this help message and exit
    -f FOO, --foo=FOO  Enable foo

Positional Arguments:
  bar  The bar positional argument
  baz  The baz positional argument

#2


8  

Try taking a look at argparse. Documentation says it supports position arguments and nicer looking help messages.

试试看argparse。文档说它支持位置参数和更好看的帮助消息。

#3


1  

I'd be interested in a clean solution to this; I wasn't able to come up with one. The OptionParser really focuses entirely on the options; it doesn't give you anything to work with position args, as far as I've been able to find.

我对这个干净的解决方案感兴趣;我无法想出一个。 OptionParser完全专注于选项;据我所知,它并没有给你任何与位置算法有关的东西。

What I did was to generate a list of little documentation blocks for each of my positional arguments, using \ts to get the right spacing. Then I joined them with newlines, and appended that to the 'usage' string that gets passed to the OptionParser.

我所做的是为每个位置参数生成一个小文档块列表,使用\ ts来获得正确的间距。然后我用newlines加入它们,并将其附加到传递给OptionParser的'usage'字符串。

It looks fine, but it feels silly, and of course that documentation ends up appearing above the list of options. I haven't found any way around that, or how to do any complex stuff, i.e. a given set of options is described beneath the description for a positional arg, because they only apply to that arg.

它看起来很好,但感觉很愚蠢,当然文档最终出现在选项列表之上。我没有找到任何方法,或者如何做任何复杂的事情,即在位置arg的描述下面描述了一组给定的选项,因为它们只适用于那个arg。

I looked at monkey-patching OptionParser's methods and I remember (this was a year or so ago) that it wouldn't have been that difficult, but I didn't want to go down that path.

我看了一下猴子修补OptionParser的方法,我记得(这是大约一年前),它不会那么困难,但我不想走那条路。

#4


0  

Most help text for positional arguments resembles the format frequently used in man pages for *NIX boxes. Take a look at how the 'cp' command is documented. Your help text should resemble that.

位置参数的大多数帮助文本类似于* NIX框的手册页中经常使用的格式。看看如何记录'cp'命令。您的帮助文本应该类似于此。

Otherwise as long as you fill out the "help" argument while using the parser, the documentation should produce itself.

否则,只要您在使用解析器时填写“帮助”参数,文档就应该自行生成。