首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >按字母顺序排序argparse帮助

按字母顺序排序argparse帮助
EN

Stack Overflow用户
提问于 2012-09-05 01:34:29
回答 4查看 3.3K关注 0票数 24

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

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

代码语言:javascript
复制
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()

当作为python script -h调用时,它会生成:

代码语言:javascript
复制
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按字母顺序添加条目来手动维护,但我正在努力避免这样做。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-09-05 02:13:20

您可以通过提供一个定制的HelpFormatter class来做到这一点;其内部内容没有正式的文档记录。这意味着当涉及到Python版本与版本之间的兼容性时,您只能靠自己,但我发现该接口相当稳定:

代码语言:javascript
复制
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选项一样。

以下哪项输出:

代码语言:javascript
复制
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
票数 25
EN

Stack Overflow用户

发布于 2012-09-05 01:59:12

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

显然,您可以使用提供的格式化程序之一,但不能在不进行一点反向工程的情况下覆盖和替换它们:

代码语言:javascript
复制
>>> 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.
票数 1
EN

Stack Overflow用户

发布于 2012-09-05 21:33:24

这类似于@mgilson的答案。我以为我早些时候已经发布了这篇文章,但显然不是。

代码语言:javascript
复制
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的公开文档接口,但在定义解析器的过程中增加了一层。(根据您的理念,将有关选项的信息从解析器的实现中分离出来可能是件好事。)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12268602

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档