我提出了一个补丁(或者更确切地说是补丁),可以让您测试参数的一般逻辑组合。http://bugs.python.org/issue11588
.
我的想法的核心是在里面添加一个钩子parse_args
允许用户测试参数的所有逻辑组合。此时它可以访问列表seen
论据。您在外部无法查看此列表parse_args
(因此需要一个钩子)。但只要有适当的defaults
,您可以编写自己的测试,使用args
命名空间。
实施一般性规定的困难argparse
版本包括:
a)实现某种嵌套组(在您的情况下有几个any
嵌套在一个内的组xor
group)
b) 以有意义的方式显示这些组usage
line
目前,您最好的选择是使用子解析器来实现您的问题(如果适合),或者在解析后进行自己的测试。并写你自己的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)
If the count
为 0,则没有找到任何组,如果1
已找到一组,等等。hook
我在错误问题中提到的进行了相同类型的测试,只是使用了不同的present
test.
正常的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')
IE。的某种组合any
,all
,and
,or
. But count
是一个很好的处理方式xor
健康)状况。