排序argparse帮助字母 [英] Sort argparse help alphabetically
问题描述
我使用Python的(2.7)argparse设施,并想自动排序它通过选项的字母顺序产生帮助。
I am using Python's (2.7) argparse facility and would like to automatically sort the help it produces alphabetically by option.
在默认情况下帮助条目在它们被添加*的顺序进行排序,如:
By default help entries are sorted in the order they are added*, as in:
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脚本称为-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,首先,H,插补,对称号。
Is it possible to automatically sort them alphabetically instead? This would be dur, first, h, interp, title.
*显然,解决办法是手动加入使用p.add_argument按字母顺序添加的条目维护,但我想避免这样做。
*Obviously the work around is to manually maintain by adding entries using p.add_argument in alphabetical added order but I am trying to avoid doing so.
推荐答案
您可以通过提供一个自定义的 HelpFormatter
类;它的内部被正式无证。这意味着你是你自己,当它从Python版本到版本的兼容性,但我发现界面相当稳定:
You can do this by providing a custom HelpFormatter
class; the internals of which are officially undocumented. This means you are on your own when it comes to compatibility from Python version to version, but I find the interface quite stable:
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,
)
下面我排序的选项字符串((' - 杜尔','-d')
等),但你可以随你挑,以什么要排序的。这个简单的排序选项放单短线最后的选项,如 -h
选项。
Here I sort on the option strings (('--dur', '-d')
, etc.), but you could take your pick as to what you want to sort on. This simple sorting option puts the single-dash options last, like the -h
option.
它输出:
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
这篇关于排序argparse帮助字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!