import argparse
parent_parser = argparse.ArgumentParser(description="The parent parser")
parent_parser.add_argument("-p", type=int, required=True,
help="set db parameter")
subparsers = parent_parser.add_subparsers(title="actions")
parser_create = subparsers.add_parser("create", parents=[parent_parser],
add_help=False,
description="The create parser",
help="create the orbix environment")
parser_create.add_argument("--name", help="name of the environment")
parser_update = subparsers.add_parser("update", parents=[parent_parser],
add_help=False,
description="The update parser",
help="update the orbix environment")
这将生成以下格式的帮助消息:
parent_parser.print_help()
输出:
usage: main.py [-h] -p P {create,update} ...
The parent parser
optional arguments:
-h, --help show this help message and exit
-p P set db parameter
actions:
{create,update}
create create the orbix environment
update update the orbix environment
parser_create.print_help()
输出:
usage: main.py create [-h] -p P [--name NAME] {create,update} ...
The create parser
optional arguments:
-h, --help show this help message and exit
-p P set db parameter
--name NAME name of the environment
actions:
{create,update}
create create the orbix environment
update update the orbix environment
但是,如果您运行程序,则如果未指定操作(即create
或update
),则不会遇到错误。如果您希望这种行为,请按如下所示修改您的代码。
<...>
subparsers = parent_parser.add_subparsers(title="actions")
subparsers.required = True
subparsers.dest = 'command'
<...>
由于自2011年以来处理次解析器的变化,将主解析器用作并不是一个好主意parent
。更一般而言,不要尝试dest
在主解析器和子解析器中定义相同的参数(相同)。子解析器的值将覆盖主设置的所有内容(即使子解析器default
也可以这样做)。创建单独的解析器以用作parents
。并且如文档中所示,父母应使用add_help=False
。