Argparse是否支持多个互斥的参数?

2024-04-24 11:09:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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


Tags: 模块方法add参数数量groupargparseexclusive
1条回答
网友
1楼 · 发布于 2024-04-24 11:09:28

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

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

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

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

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

现在,最好的办法是用子parser实现您的问题(如果合适的话),或者在解析之后进行自己的测试。写你自己的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找到了一个组,等等。我在bug问题中提到的hook执行相同类型的测试,只是使用了不同的present测试。在

如果计数mutually exclusive,则正常的mutually exclusive测试将反对。一个必需的组会反对0,等等

^{pr2}$

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

相关问题 更多 >