分享

python中使用argparse.add_argument_group() 对命令行参数进行概念性分组

 启辰ozkb3yjim4 2018-09-29
当你通过ArgumentParser()创建一个参数解析器并在执行程序带有-h参数时,你将会看到系统生成的自动帮助信息,这些信息用于帮助用户了解这些参数的用意和用法。默认情况下,位置参数和条件参数会被分为两个分组,例如,下面是一个简单的脚本(example.py)以及这个脚本运行python example.py -h的输出。
import argparse
parser = argparse.ArgumentParser(description='Simple example')
parser.add_argument('name', help='Who to greet', default='World')
parser.add_argument('--bar_this')
parser.add_argument('--bar_that')
parser.add_argument('--foo_this')
parser.add_argument('--foo_that')
args = parser.parse_args()
usage: example.py [-h] [--bar_this BAR_THIS] [--bar_that BAR_THAT]
 [--foo_this FOO_THIS] [--foo_that FOO_THAT]
 name
Simple example
positional arguments:
 name Who to greet
optional arguments:
 -h, --help show this help message and exit
 --bar_this BAR_THIS
 --bar_that BAR_THAT
 --foo_this FOO_THIS
 --foo_that FOO_THAT

某些情况下,你想要将参数划分到进一步的概念分组中,以便帮助你的用户。例如,你可能希望所有的输入选项在一个分组中,所有的输出格式选项在另外一个分组中。上面的例子可以按照前缀(--foo_或者--bar_)调整分组。
import argparse
parser = argparse.ArgumentParser(description='Simple example')
parser.add_argument('name', help='Who to greet', default='World')
# 创建两个分组
foo_group = parser.add_argument_group(title='Foo options')
bar_group = parser.add_argument_group(title='Bar options')
# 添加参数到这些分组中
foo_group.add_argument('--bar_this')
foo_group.add_argument('--bar_that')
bar_group.add_argument('--foo_this')
bar_group.add_argument('--foo_that')
args = parser.parse_args()
上面的代码运行python example.py -h 后的生成的输出是:
usage: example.py [-h] [--bar_this BAR_THIS] [--bar_that BAR_THAT]
 [--foo_this FOO_THIS] [--foo_that FOO_THAT]
 name
Simple example
positional arguments:
 name Who to greet
optional arguments:
 -h, --help show this help message and exit
Foo options:
 --bar_this BAR_THIS
 --bar_that BAR_THAT
Bar options:
 --foo_this FOO_THIS
 --foo_that FOO_THAT

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多