如何在带有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)
我想要拥有的是来自单独子命名空间或dict中每个子解析器的值,例如
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).
如何使用相同名称空间(示例中为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屋!