Python argparse:我如何单独获取参数组的Namespace对象?

shi*_*shu 11 python argparse

我有一些按组分类的命令行参数如下:

cmdParser = argparse.ArgumentParser()
cmdParser.add_argument('mainArg')

groupOne = cmdParser.add_argument_group('group one')
groupOne.add_argument('-optA')
groupOne.add_argument('-optB')

groupTwo = cmdParser.add_argument_group('group two')
groupTwo.add_argument('-optC')
groupTwo.add_argument('-optD')
Run Code Online (Sandbox Code Playgroud)

我如何解析上面的内容,以便最终得到三个不同的Namespace对象?

global_args - containing all the arguments not part of any group
groupOne_args - containing all the arguments in groupOne
groupTwo_args - containing all the arguments in groupTwo
Run Code Online (Sandbox Code Playgroud)

谢谢!

hpa*_*ulj 5

没有任何东西argparse是为了做到这一点而设计的。

对于它的价值,parser从两个参数组开始,一个显示为,另一个显示positionalsoptionals(我忘记了确切的标题)。所以在你的例子中,实际上会有 4 个组。

解析器仅在格式化帮助时使用参数组。为了解析所有参数都放在一个主parser._actions列表中。在解析过程中,解析器只传递一个命名空间对象。

您可以使用不同的参数集定义单独的解析器,并使用parse_known_args. 使用optionals(标记的)参数比使用positionals. 它会分散您的帮助。

我已经在其他SO问题,探索出了一条新的Namespace,可能基于某种点缀巢值类dest(如姓名group1.optAgroup2.optC等等)。我不记得我是否必须自定义Action类。

基本点是,当将值保存到命名空间时,解析器或实际上是Action(参数)对象会:

setattr(namespace, dest, value)
Run Code Online (Sandbox Code Playgroud)

那(和 getattr/hasattr)就是解析器对namespace. 默认Namespace类很简单,只不过是一个普通的object子类。但它可以更详细。


小智 5

您可以通过以下方式进行操作:

import argparse
parser = argparse.ArgumentParser()

group1 = parser.add_argument_group('group1')
group1.add_argument('--test1', help="test1")

group2 = parser.add_argument_group('group2')
group2.add_argument('--test2', help="test2")

args = parser.parse_args('--test1 one --test2 two'.split())

arg_groups={}

for group in parser._action_groups:
    group_dict={a.dest:getattr(args,a.dest,None) for a in group._group_actions}
    arg_groups[group.title]=argparse.Namespace(**group_dict))
Run Code Online (Sandbox Code Playgroud)

这将为您提供普通的args,以及包含每个已添加组的名称空间的字典arg_groups。

(改编自此答案