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)
我提出了一个补丁(或者更确切地说是补丁),它可以让你测试参数的一般逻辑组合。
http://bugs.python.org/issue11588
。在我想法的核心是在
parse_args
内添加一个钩子,让用户测试参数的所有逻辑组合。此时它可以访问一个列表seen
参数。此列表在parse_args
之外对您不可用(因此需要一个钩子)。但是使用适当的defaults
,您可以编写使用args
命名空间的自己的测试。在实现通用
argparse
版本的困难包括:a)实现某种嵌套组(在您的例子中,有几个
any
组嵌套在一个xor
组中)b)在有意义的
usage
行中显示这些组现在,最好的办法是用子parser实现您的问题(如果合适的话),或者在解析之后进行自己的测试。写你自己的
usage
。在下面是一个通用化测试的草图,它可以在解析后应用于
args
命名空间如果
count
为0,则没有找到任何组,如果1
找到了一个组,等等。我在bug问题中提到的hook
执行相同类型的测试,只是使用了不同的present
测试。在如果计数
^{pr2}$mutually exclusive
,则正常的mutually exclusive
测试将反对。一个必需的组会反对0
,等等即
any
,all
,and
,or
的组合。但是count
是处理xor
条件的好方法。在相关问题 更多 >
编程相关推荐