猿问

argparse:在命令“帮助”中设置选项 arg 的名称

在 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()


但是,在显示帮助时,不是将 arg 指定为其名称,而是将其指定为{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


我怎样才能让他显示 arg 的名称,所以输出更像



positional arguments:

  action                The action to do. Eligible values: install, remove,

                        version


optional arguments:

  -h, --help            show this help message and exit


狐的传说
浏览 118回答 2
2回答

桃花长相依

metavar参数 toadd_argument是您正在寻找的: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] actionpositional arguments:  action      The action to do. Eligible values: install, remove, versionoptional arguments:  -h, --help  show this help message and exit

holdtom

您可以指定元变量当 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'])
随时随地看视频慕课网APP

相关分类

Python
我要回答