我提出了一个补丁(或者更确切地说是补丁),可以让您测试参数的一般逻辑组合。 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 测试。
如果计数>1,正常的mutually exclusive 测试会反对。一个必需的组会反对0,等等。你也可以做类似的事情
if (present(args.x1) or present(args.x2)) and
(present(args.y1) or present(args.y2)):
parser.error('too many groups')
即。 any,all,and,or 的某种组合。但是count 是处理xor 条件的好方法。