如何使用 argparse 在单独的命名空间中拥有子解析器参数? [英] How to have sub-parser arguments in separate namespace with argparse?
问题描述
我有以下测试代码
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", default = 0, type=int)
subparsers = parser.add_subparsers(dest = "parser_name")
parser_lan = subparsers.add_parser('car')
parser_lan.add_argument("--boo")
parser_lan.add_argument("--foo")
parser_serial = subparsers.add_parser('bus')
parser_serial.add_argument("--fun")
print parser.parse_args()
定义了两个子解析器,具有不同的参数集.当我将测试代码称为
which defines two sub-parsers, having a different set of arguments. When I call the testcode as
tester.py --verbose 3 car --boo 1 --foo 2
我得到了预期的结果
Namespace(boo='1', foo='2', parser_name='car', verbose=3)
我想要的是来自单独命名空间或字典中的每个子解析器的值,例如
What I want to have instead is the values from each subparser in a separate namespace or dict, something like
Namespace(subparseargs={boo:'1', foo:'2'}, parser_name='car', verbose=3)
以便来自每个子解析器的参数与来自主解析器的参数在逻辑上分开(如本例中的 verbose
).
so that the arguments from each subparser are logical separated from the arguments from the main parser (as verbose
in this example).
如何使用 same 命名空间中的每个子解析器的参数(在示例中为 subparseargs
)来实现这一点.
How can I achieve this, with the arguments for each subparser in the same namespace (subparseargs
in the example).
推荐答案
我已经开始开发一种不同的方法(但类似于 Anthon 的建议)并提出了一个更短的代码.但是,我不确定我的方法是否是该问题的通用解决方案.
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.
类似于 Anthon 的提议,我定义了一个新方法,该方法创建了一个顶级"参数列表,这些参数保存在 args
中,而所有其他参数作为附加字典返回:
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.
这篇关于如何使用 argparse 在单独的命名空间中拥有子解析器参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!