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

Python argparse互斥组

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

Python argparse互斥组

add_mutually_exclusive_group
不会使整个组互斥。它使组内的选项互斥。

您正在寻找的是子命令。而不是编[-a xxxx | [-b yyy -c zzz]],您将拥有:

prog   command 1     -a: ...  command 2    -b: ...    -c: ...

要使用第一组参数进行调用:

prog command_1 -a xxxx

要使用第二组参数进行调用:

prog command_2 -b yyyy -c zzzz

您还可以将子命令参数设置为位置。

prog command_1 xxxx

有点像git或svn:

git commit -amgit merge develop

工作范例

# create the top-level parserparser = argparse.ArgumentParser(prog='PROG')parser.add_argument('--foo', action='store_true', help='help for foo arg.')subparsers = parser.add_subparsers(help='help for subcommand')# create the parser for the "command_1" commandparser_a = subparsers.add_parser('command_1', help='command_1 help')parser_a.add_argument('a', type=str, help='help for bar, positional')# create the parser for the "command_2" commandparser_b = subparsers.add_parser('command_2', help='help for command_2')parser_b.add_argument('-b', type=str, help='help for b')parser_b.add_argument('-c', type=str, action='store', default='', help='test')

测试一下

>>> parser.print_help()usage: PROG [-h] [--foo] {command_1,command_2} ...positional arguments:  {command_1,command_2}  help for subcommand    command_1command_1 help    command_2help for command_2optional arguments:  -h, --help show this help message and exit  --foo      help for foo arg.>>>>>> parser.parse_args(['command_1', 'working'])Namespace(a='working', foo=False)>>> parser.parse_args(['command_1', 'wellness', '-b x'])usage: PROG [-h] [--foo] {command_1,command_2} ...PROG: error: unrecognized arguments: -b x

祝好运。



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

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

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