如何在argparse互斥组中包含一个位置参数? [英] How to include one positional argument into argparse mutually exclusive group?
问题描述
我知道在一个互斥的组中使用多个位置参数是没有意义的,因为您不能说谁是谁.但是我需要在其中加入一个位置参数.
I know that does not make sense multiple positional arguments into a mutually exclusive group because you can't say who is who. But I need to include ONE positional argument into that.
我需要什么:
$ myprogram -h
usage: myprogram [-h] [--delete value | --update value | value]
其中位置value
是默认操作(种类为"--include"). (没有参数的myprogram
也必须是有效的.)
Where positional value
is the default action (kind of "--include"). (myprogram
without arguments must be valid too).
我的第一次尝试(无效):
My first attempt (this doesn't works):
parser = ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('--delete', metavar='value')
group.add_argument('--update', metavar='value')
group.add_argument('value')
有可能吗?
第二次尝试:
parser = ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('--delete', action='store_true')
group.add_argument('--update', action='store_true')
group.add_argument('--insert', action='store_true', default=True)
group.add_argument('value')
推荐答案
我会做一些不同的事情:
I'd do this a little bit differently:
parser = ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.set_defaults(mode='insert')
group.add_argument('--delete', action='store_const', dest='mode', const='delete')
group.add_argument('--update', action='store_const', dest='mode', const='update')
group.add_argument('--insert', action='store_const', dest='mode', const='insert')
parser.add_argument('value', nargs='?')
args = parser.parse_args()
如果您还想使program --delete
(没有value
选项)失败,请添加
If you additionally want to make program --delete
(with no value
option) fail, add
if args.mode != 'insert' and args.value:
parser.error("can't {} without a value argument".format(args.mode))
请注意,这将意味着program --insert
(无value
)仍然有效.您可以通过将默认值mode
设置为None
,使用args.mode is not None
进行上述检查,然后再进行if args.mode is None: args.mode = 'insert'
或类似的操作来避免这种情况.
Note that this will mean that program --insert
(with no value
) still works. You could avoid this with a little more effort by having the default mode
be None
, doing the check above with args.mode is not None
, and then doing if args.mode is None: args.mode = 'insert'
or similar.
这篇关于如何在argparse互斥组中包含一个位置参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!