使用 argparse 时,子解析器本质上是互斥的吗? [英] With argparse are subparsers inherently mutually exclusive?
问题描述
我有一个包含两个主要功能的脚本,升级和配置.我使用子解析器作为指示脚本执行的操作的一种方式,但我想避免将它们一起使用.
I have a script with two primary functions, upgrade and provision. I'm using subparsers as a way to dictate the action being performed by the script but I want to avoid them being used together.
这是代码片段:
import argparse
def main():
parser = argparse.ArgumentParser()
subparser = parser.add_subparsers(help='sub-command help')
parser.add_argument('--user', '-u', help='User', default=None, required=True)
parser.add_argument('--password', '-p', help='Password', default=None, required=True)
parser.add_argument('--server', '-s', help='server with Admin functionality', default=None, required=True)
subparser_prov = subparser.add_parser('provision', help='Provision new managers')
subparser_prov.set_defaults(which='provision')
subparser_upgr = subparser.add_parser('upgrade', help='Upgrade worker by replacing them')
subparser_upgr.set_defaults(which='upgrade')
subparser_upgr.add_argument('--version', help='Deployment version', default=None)
args = vars(parser.parse_args())
print args['user']
print args['password']
if args['which'] == 'provision':
print 'Provisioning new environment!'
elif args['which'] == 'upgrade':
print 'Upgrading workers! %s' % args['version']
if __name__ == "__main__":
main()
我知道解析器和子解析器都支持 add_mutually_exclusive_group() ,但这专门用于参数.使用子解析器有什么方法可以避免它们一起使用吗?
I know that add_mutually_exclusive_group() is supported by both parser and subparser however this is specifically for arguments. With a subparser is there any method for avoiding them being used together?
推荐答案
是的,它们是相互排斥的,尽管机制与 MXGroups 不同.
Yes, they are mutually exclusive, though the mechanism is different from the MXGroups.
subparser = parser.add_subparsers(help='sub-command help')
是一个 add_argument
命令,它创建一个 positional
参数,带有一个特殊的 action
类.除此之外,它还有一个 choices
值.
is an add_argument
command that creates a positional
argument, with a special action
class. Among other things it has a choices
value.
subparser.add_parser(...)
创建一个 parser
,并将其名称"(和别名)添加到 subparser
的 choices
中.
creates a parser
, and adds its 'name' (and aliases) to subparser
's choices
.
一个位置参数只解析一次,所以只会处理一个子解析器.并且子解析器通常会处理所有剩余的参数.
A positional argument is parsed only once, so only one subparser will be handled. And the subparser usually processes all of the remaining arguments.
有很多问题要解决这个问题——那就是他们想要处理多个子解析器.这样做的方法很棘手,涉及递归(或重复)调用解析器,每次使用较小的原始参数集.
There have been SO questions that ask about getting around that - that is they want to handle multiple subparsers. The way to do that is tricky, and involves calling a parser recursively (or repeatedly), each time with a smaller set of the original arguments.
这篇关于使用 argparse 时,子解析器本质上是互斥的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!