Argparse: 如何在命令“help”中设置一个选项参数的名称

3
在argparse中,可以通过如下代码创建一个选择参数:
parser = argparse.ArgumentParser()
parser.add_argument("action", type=str,
                    help="The action to do. Eligible values:\ninstall, remove, version", choices=['install', 'remove', 'version'])

parser 是一个 argparse.ArgumentParser() 的实例时

然而,在显示帮助时,参数不是按照名称指定,而是指定为 {install,remove,version},整个输出如下:


positional arguments:
  {install,remove,version}
                        The action to do. Eligible values: install, remove,
                        version

optional arguments:
  -h, --help            show this help message and exit


我该如何使其显示参数的名称,以便输出更像:

positional arguments:
  action                The action to do. Eligible values: install, remove,
                        version

optional arguments:
  -h, --help            show this help message and exit
2个回答

2
您可以指定 metavar
引用:
当 ArgumentParser 生成帮助信息时,需要一些方式来引用每个期望的参数。默认情况下,[...] 可以使用 metavar 指定替代名称:
parser = argparse.ArgumentParser()
parser.add_argument("action", type=str, metavar='action',
                    help="The action to do. Eligible values:\ninstall, remove, version", choices=['install', 'remove', 'version'])

2
< p > add_argument方法的metavar参数是您要查找的内容:

parser = argparse.ArgumentParser()
parser.add_argument(
    "action",
    type=str,
    help="The action to do. Eligible values:\ninstall, remove, version",
    choices=['install', 'remove', 'version'],
    metavar="action",
)

调用parser.print_help()会产生以下结果:

usage: [-h] action

positional arguments:
  action      The action to do. Eligible values: install, remove, version

optional arguments:
  -h, --help  show this help message and exit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接