python argparse:在-h中定义选择

pythons argparse: define choices in -h

我正在为我的程序构建命令行 argparser,我尝试在 -h 选项中提供更多细节

我有以下代码:

import argparse
legal_actions = ['act1', 'act2', 'act3']
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(help='available commands')

    parser_cmd = subparsers.add_parser("cmd")

    parser_cmd.add_argument("-a", "--action", type=str, metavar="", choices=legal_actions, required=True,
                            help='list of actions: {%(choices)s}')
    parser_cmd.add_argument("nargs", type=str, nargs='*',
                            help="the rest of the arguments required to perform an action")
    parser_cmd.set_defaults(func=cmd_handler)

python prog.py cmd -h 将在命令行中产生以下打印结果

usage: cmd [-h] -a  [nargs [nargs ...]]

positional arguments:
  nargs           the rest of the arguments required to perform an action

optional arguments:
  -h, --help      show this help message and exit
  -a , --action   list of actions: {act1, act2, act3}

每个动作都需要不同数量的参数,因此我想添加一些内容来描述动作(来自动作列表),例如:

actions availble:
    act1: requires 2 arguments (arg1, arg2)
    act2: requires 0 arguments ()
    act3: requires 1 arguments (arg1)

而且我希望它与上面的 "optional arguments" 有任何 link,所以很容易看到 "acts" 在 -a 选项下

]

如果要添加更多信息,可以使用epilog-参数:

from argparse import RawDescriptionHelpFormatter  # This is used to enable newlines in epilogs and descriptions(\n)
from argparse import ArgumentParser

description = 'Some description of program'
epilog = 'actions availble:\n\t'
epilog += 'act1: requires 2 arguments (arg1, arg2)\n\t'
epilog += 'act2: requires 0 arguments ()\n\t'
epilog += 'act3: requires 1 arguments (arg1)'

parser = argparse.ArgumentParser(description=description, epilog=epilog, 
                                formatter_class=RawTextHelpFormatter)

这将打印出

actions availble:
    act1: requires 2 arguments (arg1, arg2)
    act2: requires 0 arguments ()
    act3: requires 1 arguments (arg1)

帮助输出结束。使用 add_subparsers() 时,epilog 参数也可以包含在 add_parser() 中:

This object has a single method, add_parser(), which takes a command name and any ArgumentParser constructor arguments, and returns an ArgumentParser object that can be modified as usual.

注意:默认格式化程序将忽略换行符,因此请查看 Python argparse: How to insert newline in the help text? 解决此问题的位置,其中描述了如何替换格式化程序 á la:

ArgumentParser(..., formatter_class=RawDescriptionHelpFormatter)

阅读 docs 中关于 epilog-parameter 的更多信息。