请问add_mutually_exclusive_group函数什么意思?

参考请问add_mutually_exclusive_group函数什么意思? - 云+社区 - 腾讯云

创建一个互斥组。 argparse 将会确保互斥组中只有一个参数在命令行中可用:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> group = parser.add_mutually_exclusive_group()
>>> group.add_argument('--foo', action='store_true')
>>> group.add_argument('--bar', action='store_false')
>>> parser.parse_args(['--foo'])
Namespace(bar=True, foo=True)
>>> parser.parse_args(['--bar'])
Namespace(bar=False, foo=False)
>>> parser.parse_args(['--foo', '--bar'])
usage: PROG [-h] [--foo | --bar]
PROG: error: argument --bar: not allowed with argument --foo

add_mutually_exclusive_group() 方法也接受一个 required 参数,表示在互斥组中至少有一个参数是需要的:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> group = parser.add_mutually_exclusive_group(required=True)
>>> group.add_argument('--foo', action='store_true')
>>> group.add_argument('--bar', action='store_false')
>>> parser.parse_args([])
usage: PROG [-h] (--foo | --bar)
PROG: error: one of the arguments --foo --bar is required
 

注意,目前互斥参数组不支持 add_argument_group()titledescription 参数。

猜你喜欢

转载自blog.csdn.net/weixin_36670529/article/details/113783239