我正在使用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()
当作为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按字母顺序添加条目来手动维护,但我正在努力避免这样做。
发布于 2012-09-05 02:13:20
您可以通过提供一个定制的HelpFormatter
class来做到这一点;其内部内容没有正式的文档记录。这意味着当涉及到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-05 01:59:12
在创建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-05 21:33:24
这类似于@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
的公开文档接口,但在定义解析器的过程中增加了一层。(根据您的理念,将有关选项的信息从解析器的实现中分离出来可能是件好事。)
https://stackoverflow.com/questions/12268602
复制相似问题