argparse 是否支持多个独占参数?

Does argparse support multiple exclusive arguments?

假设我有两组论据。您可以使用每个组中的任意数量的参数,但不能在组之间混合使用参数。

有没有办法自定义 argparse 模块中的冲突参数?我试过使用方法 add_mutually_exclusive_group 但这不是我要找的。

我提出了一个补丁(或者更确切地说是补丁),可以让您测试参数的一般逻辑组合。 http://bugs.python.org/issue11588.

我的想法的核心是在 parse_args 中添加一个挂钩,让用户测试参数的所有逻辑组合。此时它可以访问列表 seen 参数。此列表在 parse_args 之外对您不可用(因此需要挂钩)。但是通过适当的 defaults,您可以编写自己的使用 args 命名空间的测试。

实施通用 argparse 版本的困难包括:

a) 实现某种嵌套组(在你的例子中,几个 any 组嵌套在一个 xor 组中)

b) 在有意义的 usage 行中显示这些组

现在你最好的选择是要么用子解析器实现你的问题(如果它适合),要么在解析后进行你自己的测试。并写下你自己的 usage.

这是一个通用测试的草图,可以在解析后应用于 args 名称空间

def present(a):
    # test whether an argument is 'present' or not
    # simple case, just check whether it is the default None or not
    if a is not None:
        return True
    else:
        return False

# sample namespace from parser
args = argparse.Namespace(x1='one',x2=None,y1=None,y2=3)

# a nested list defining the argument groups that need to be tested
groups=[[args.x1,args.x2],[args.y1,args.y2]]

# a test that applies 'any' test to the inner group
# and returns the number of groups that are 'present'
[any(present(a) for a in g) for g in groups].count(True)

如果 count 为 0,则找不到任何组,如果 1 找到一个组,等等。我在错误问题中提到的 hook 也是如此某种测试,只是使用不同的 present 测试。

正常的 mutually exclusive 测试会反对如果计数 >1。一个必需的组会反对 0,等等。你也可以做类似

的事情
if (present(args.x1) or present(args.x2)) and 
   (present(args.y1) or present(args.y2)): 
   parser.error('too many groups')

即。 anyallandor 的某种组合。但是 count 是处理 xor 条件的好方法。