argparse:必需组中的一些互斥参数

Nil*_*Nil 14 python argparse

我有一组参数可以在逻辑上分为两组:

  • 操作:A1,A2,A3等.
  • 信息:I1,I2,I3等.

程序启动时至少需要其中一个参数,但"信息"参数可以与"动作"参数一起使用.所以

  • 操作或信息中至少需要一个
  • 所有行动都是互斥的

我找不到如何使用argparse来做到这一点.我知道add_mutually_exclusive_group它和它的required论点,但我不能在"行动"上使用它,因为它实际上并不是必需的.当然,我可以在argparse之后添加一个条件来手动检查我的规则,但它看起来像是一个黑客.argparse可以这样做吗?

编辑:对不起,这里有一些例子.

# Should pass
--A1
--I1
--A1 --I2
--A2 --I1 --I2

# Shouldn't pass
--A1 --A2
--A1 --A2 --I1
Run Code Online (Sandbox Code Playgroud)

che*_*ner 4

在解析参数后验证它们并没有什么奇怪的。只需将它们全部收集到一组中,然后确认它不为空并且最多包含一个操作。

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")
Run Code Online (Sandbox Code Playgroud)