您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python argparse-向多个子解析器添加参数

Python argparse-向多个子解析器添加参数

这可以通过定义一个包含公共选项的父解析器来实现:

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

但是,如果您运行程序,则如果未指定操作(即createupdate),则不会遇到错误。如果您希望这种行为,请按如下所示修改您的代码

<...>
subparsers = parent_parser.add_subparsers(title="actions")
subparsers.required = True
subparsers.dest = 'command'
<...>

由于自2011年以来处理次解析器的变化,将主解析器用作并不是一个好主意parent。更一般而言,不要尝试dest在主解析器和子解析器中定义相同的参数(相同)。子解析器的值将覆盖主设置的所有内容(即使子解析器default也可以这样做)。创建单独的解析器以用作parents。并且如文档中所示,父母应使用add_help=False

python 2022/1/1 18:30:12 有193人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶