您可以通过提供一个自定义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