2015-04-28 42 views
2

假设我有两组参数。您可以使用来自每个组的任意数量的参数,但不能在组之间混合参数。argparse是否支持多个独占参数?

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

+0

不,argparse不支持该开箱即用的应用程序。你必须单独检查。 –

+0

有没有可以做到这一点的模块? – user3056783

+0

我不知道,对不起。 –

回答

3

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

我的想法的核心是在parse_args内部添加一个钩子,它允许用户测试所有参数的逻辑组合。在这点上它有权访问列表seen参数。这个列表在parse_args以外不可用(因此需要钩子)。但通过合适的defaults,您可以编写自己的使用args命名空间的测试。

与实施一般​​版本的困难包括:

一)实施某种形式的嵌套组(在你的情况下,几个any组一个xor组内嵌套)

B)显示在这些组有意义的usage line

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

这里有一个概括的测试,可以解析

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之后被应用到args命名空间的草图,没有组发现,如果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') 

ie。 any,all,and,or的某种组合。但是count是处理xor条件的好方法。