24

我正在使用 Python 的 (2.7) argparse 工具,并希望自动按选项按字母顺序对它生成的帮助进行排序。

默认情况下,帮助条目按添加顺序排序*,如下所示:

p = argparse.ArgumentParser(description='Load duration curves and other plots')
p.add_argument('--first', '-f', type=int, default=1, help='First Hour')
p.add_argument('--dur', '-d', type=int, default=-1, help='Duration in Hours. Use -1 for all')
p.add_argument('--title', '-t', help='Plot Title (for all plots), default=file name')
p.add_argument('--interp', '-i', action="store_true", default=True, 
                help='Use linear interpolation for smoother curves')
...
args = p.parse_args()

当调用 as 时python script -h产生:

usage: script.py [-h] [--first FIRST] [--dur DUR] [--title TITLE] [--interp]

Load duration curves and other plots

optional arguments:
  -h, --help            show this help message and exit
  --first FIRST, -f FIRST
                        First Hour
  --dur DUR, -d DUR     Duration in Hours. Use -1 for all
  --title TITLE, -t TITLE
                        Plot Title (for all plots), default=file name
  --interp, -i          Use linear interpolation for smoother curves

是否可以自动按字母顺序对它们进行排序?这将是 dur, first, h, interp, title。

*显然,解决方法是通过使用 p.add_argument 按字母顺序添加条目来手动维护,但我试图避免这样做。

4

5 回答 5

26

您可以通过提供自定义HelpFormatter来做到这一点;其中的内部结构没有正式记录。这意味着当涉及到 Python 版本与版本之间的兼容性时,您需要靠自己,但我发现界面相当稳定:

from argparse import HelpFormatter
from operator import attrgetter

class SortingHelpFormatter(HelpFormatter):
    def add_arguments(self, actions):
        actions = sorted(actions, key=attrgetter('option_strings'))
        super(SortingHelpFormatter, self).add_arguments(actions)


p = argparse.ArgumentParser(...
    formatter_class=SortingHelpFormatter,
)

在这里,我对选项字符串(('--dur', '-d')等)进行排序,但您可以选择要排序的内容。这个简单的排序选项将单破折号选项放在最后,就像-h选项一样。

输出:

usage: [-h] [--first FIRST] [--dur DUR] [--title TITLE] [--interp]

Load duration curves and other plots

optional arguments:
  --dur DUR, -d DUR     Duration in Hours. Use -1 for all
  --first FIRST, -f FIRST
                        First Hour
  --interp, -i          Use linear interpolation for smoother curves
  --title TITLE, -t TITLE
                        Plot Title (for all plots), default=file name
  -h, --help            show this help message and exit
于 2012-09-04T18:13:19.967 回答
1

创建 ArgumentParser 类时,您可以传入帮助格式化程序: http: //docs.python.org/library/argparse.html#formatter-class

因此,显然您可以使用提供的格式化程序之一,但不能在没有逆向工程的情况下覆盖和替换它们:

>>> h = argparse.ArgumentDefaultsHelpFormatter
>>> print h.__doc__
Help message formatter which adds default values to argument help.

    Only the name of this class is considered a public API. All the methods
    provided by the class are considered an implementation detail.
于 2012-09-04T17:59:11.623 回答
1

一种替代方法,绝对比@MartijnPieters 提出的更丑陋:

p = argparse.ArgumentParser()

#add arguements here

for g in p._action_groups:
    g._group_actions.sort(key=lambda x:x.dest)

将它放在try/except子句中可能会很好,因为它只是格式化帮助,因此如果这段代码在某个AttributeError或某事上失败,那么程序的执行并不重要......

于 2012-09-04T18:29:01.387 回答
1

这类似于@mgilson 的回答。我以为我之前已经发布了这个,但显然不是。

d = dict()
d['--first'] = ('-f', "type=int", "default=1", "help='First Hour'")
d['--dur'] = ('-d', type=int, default=-1, help='Duration in Hours. Use -1 for all')
# etc

for prim_option in sorted(d):
    p.add_arguments(prim_option, *d[prim_option])

您可以调整字典中确切用作键的内容,以及对 的参数sorted和调用的确切结构add_arguments,以获得所需的排序顺序。这遵循公开记录的接口argparse,但确实为定义解析器的过程增加了一层。(根据您的理念,将有关选项的信息与解析器的实现分开可能是一件好事。)

于 2012-09-05T13:33:23.870 回答
1

帮助中的参数顺序由parser.format_help方法确定:

Definition:  parser.format_help(self)
Source:
    def format_help(self):
        formatter = self._get_formatter()
        ...
        # positionals, optionals and user-defined groups
        for action_group in self._action_groups:
            formatter.start_section(action_group.title)
            formatter.add_text(action_group.description)
            formatter.add_arguments(action_group._group_actions)
            formatter.end_section()

help是通过获取一个formatter对象,然后向它添加“部分”来创建的。在这里,它遍历_action_groups,将每个放在自己的部分中,并使用add_arguments方法添加其动作(参数)。格式化程序是临时的,仅用于创建字符串(通常是多行)。

操作组包括默认的postionalsoptionals,以及用户创建的任何操作组。这些组仅用于帮助,不用于解析。因此action_group._group_actions列表可以重新排序而不影响解析。(解析器有自己的动作列表,parser._actions)。

这证实了@mgilson 的观察,即排序p._actions不会影响帮助,但排序会影响_group_actions

排序_actions将影响usage(无论是帮助的一部分还是独立的):

    # usage
    formatter.add_usage(self.usage, self._actions,
                        self._mutually_exclusive_groups)

请注意,action_groups不会传递给使用部分。使用部分会重新排序其操作,optionals首先显示,然后positionals

add_argument如果要控制位置的解析顺序以及它们在使用中的顺序,请在阶段之前/期间对参数进行排序。

如果您只想控制帮助组中的顺序,那么._group_actions可以在调用格式化程序之前或在其中重新排序列表中的内容。

还有其他关于控制usage. 例如,有些人不希望positionals订购 after optionals

我同意 Formatter 类很麻烦。但在大多数情况下,它与 Parser 类是分开的。所以它可以被重写而对解析的影响最小。现有的 Formatter 子类只是调整低级方法,即控制换行和帮助行格式化的方法。解析器和格式化程序之间的重要接口是format_usageandformat_help方法,它们相对简单和高级。

子类化

尽管@grieve 引用了警告,但人们确实将其子类化HelpFormatter以满足他们自己的需要。唯一阻止人们这样做的是某种公司政策。所有警告告诉我们的是,argparse 开发人员没有尝试想象或记录用户可能想要进行的所有更改。我什至无法列举我在过去几年中提出的建议。

于 2015-09-27T22:59:06.700 回答