Python argparse:如何分别获取参数组的命名空间对象? [英] Python argparse : How can I get Namespace objects for argument groups separately?

查看:18
本文介绍了Python argparse:如何分别获取参数组的命名空间对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have some command line arguments categorized in groups as follows:

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')

如何解析上述内容,从而得到三个不同的 Namespace 对象?

How can I parse the above, such that I end up with three different Namespace objects?

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

谢谢!

推荐答案

你可以这样做:

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)

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

This will give you the normal args, plus dictionary arg_groups containing namespaces for each of the added groups.

(改编自 这个答案)

这篇关于Python argparse:如何分别获取参数组的命名空间对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆