argparse 支持多个独占参数吗?

2023-12-10

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

有没有办法自定义冲突的参数argparse模块?我尝试过使用方法add_mutually_exclusive_group但这不是我要找的。


我提出了一个补丁(或者更确切地说是补丁),可以让您测试参数的一般逻辑组合。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健康)状况。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

argparse 支持多个独占参数吗? 的相关文章

随机推荐