Python argparse : How can I get Namespace objects for argument groups separately?

后端 未结 3 1365
一个人的身影
一个人的身影 2021-01-04 03:36

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

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

groupOne = cm         


        
3条回答
  •  心在旅途
    2021-01-04 03:48

    you can do it in this way:

    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)
    

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

    (Adapted from this answer)

提交回复
热议问题