栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/410710.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号