这可以通过定义一个包含公共选项的父解析器来实现:
import argparseparent_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 parseroptional arguments: -h, --help show this help message and exit -p P set db parameteractions: {create,update} create create the orbix environment update update the orbix environmentparser_create.print_help()输出:
usage: main.py create [-h] -p P [--name NAME] {create,update} ...The create parseroptional arguments: -h, --help show this help message and exit -p P set db parameter --name NAME name of the environmentactions: {create,update} create create the orbix environment update update the orbix environment但是,如果您运行程序,则如果未指定操作(即
create或
update),则不会遇到错误。如果您希望这种行为,请按如下所示修改您的代码。
<...>subparsers = parent_parser.add_subparsers(title="actions")subparsers.required = Truesubparsers.dest = 'command'<...>
由@hpaulj更新
由于自2011年以来处理次解析器的变化,将主解析器用作并不是一个好主意
parent。更一般而言,不要尝试
dest在主解析器和子解析器中定义相同的参数(相同)。子解析器的值将覆盖主设置的所有内容(即使子解析器
default也可以这样做)。创建单独的解析器以用作
parents。并且如文档中所示,父母应使用
add_help=False。



