How to have sub-parser arguments in separate namespace with argparse?

前端 未结 2 1286
失恋的感觉
失恋的感觉 2021-01-11 21:44

I have the following test-code

import argparse
parser = argparse.ArgumentParser()
parser.add_argument(\"--verbose\", default = 0, type=int)

subparsers = par         


        
2条回答
  •  -上瘾入骨i
    2021-01-11 22:02

    I have started to develop a different approach (but similar to the suggestion by Anthon) and come up with a much shorter code. However, I am not sure my approach is a general solution for the problem.

    To similar what Anthon is proposing, I define a new method which creates a list of 'top-level' arguments which are kept in args, while all the other arguments are returned as an additional dictionary:

    class MyArgumentParser(argparse.ArgumentParser):
        def parse_subargs(self, *args, **kw):
            # parse as usual
            args = argparse.ArgumentParser.parse_args(self, *args, **kw)
    
            # extract the destination names for top-level arguments
            topdest = [action.dest for action in parser._actions]
    
            # loop over all arguments given in args
            subargs = {}
            for key, value in args.__dict__.items():
    
                # if sub-parser argument found ...
                if key not in topdest:
    
                    # ... remove from args and add to dictionary
                    delattr(args,key)
                    subargs[key] = value
    
            return args, subargs
    

    Comments on this approach welcome, especially any loopholes I overlooked.

提交回复
热议问题