问题描述
我有一组可以在逻辑上分为两组的参数:
I have a set of arguments that can logically be separated in 2 groups:
- 动作:
A1
、A2
、A3
等 - 信息:
I1
、I2
、I3
等
- Actions:
A1
,A2
,A3
, etc. - Informations:
I1
,I2
,I3
, etc.
程序启动至少需要这些参数之一,但信息"参数可以与动作"参数一起使用.所以
At least one of these arguments is required for the program to start, but "information" args can be used with "action" args. So
- 至少需要一项操作或信息
- 所有操作都是互斥的
我找不到使用 argparse 的方法.我知道 add_mutually_exclusive_group
及其 required
参数,但我不能在操作"上使用它,因为它实际上不是必需的.当然,我可以在 argparse 之后添加一个条件来手动检查我的规则,但这似乎是一个 hack.argparse 能做到这一点吗?
I can't find how to do it using argparse. I know about add_mutually_exclusive_group
and its required
argument, but I can't use it on "Actions" because it's not actually required. Of course, I could add a condition after argparse to manually check my rules, but it seems like an hack. Can argparse do this?
抱歉,这里有一些例子.
Sorry, here are some examples.
# Should pass
--A1
--I1
--A1 --I2
--A2 --I1 --I2
# Shouldn't pass
--A1 --A2
--A1 --A2 --I1
推荐答案
在解析参数后验证参数并没有什么不妥.只需将它们全部收集在一个集合中,然后确认它不为空并且最多包含一个操作.
There's nothing hacky about verifying arguments after they've been parsed. Just collect them all in a single set, then confirm that it is not empty and contains at most one action.
actions = {"a1", "a2", "a3"}
informations = {"i1", "i2", "i3"}
p = argparse.ArgumentParser()
# Contents of actions and informations contrived
# to make the example short. You may need a series
# of calls to add_argument to define the options and
# constants properly
for ai in actions + informations:
p.add_argument("--" + ai, action='append_const', const=ai, dest=infoactions)
args = p.parse_args()
if not args.infoactions:
p.error("At least one action or information required")
elif len(actions.intersection(args.infoactions)) > 1:
p.error("At most one action allowed")
这篇关于argparse:所需组中的一些互斥参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!