按字母顺序排序argparse帮助

Bry*_*n P 19 python sorting arguments command-line-arguments argparse

我正在使用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()
Run Code Online (Sandbox Code Playgroud)

当被称为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
Run Code Online (Sandbox Code Playgroud)

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

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

Mar*_*ers 20

您可以通过提供自定义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,
)
Run Code Online (Sandbox Code Playgroud)

在这里,我对选项字符串(('--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
Run Code Online (Sandbox Code Playgroud)

  • *无辜地吹口哨* (2认同)