如何将一个位置参数包含到 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')
推荐答案
我的做法有点不同:
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屋!