嵌套参数解析器 [英] Nested ArgumentParser
问题描述
我正在尝试为命令行工具构建嵌套解析器.我目前正在使用 add_subparsers
,但对于一种特定情况,它似乎不够强大.我无法向父解析器和子解析器命令添加相同的命名参数.请参见以下示例:
I'm trying to build nested parsers for a command line tool. I'm currently using add_subparsers
, but it seems not powerful enough for one specific case. I cannot add same named arguments to both the parent parser and subparser commands. See the following example:
import argparse
argparser = argparse.ArgumentParser()
argparser.add_argument("-H", action="store_true")
subparser = argparser.add_subparsers(dest='sp')
cmd = subparser.add_parser("cmd")
cmd.add_argument("-H")
print argparser.parse_args()
然后,运行
py test.py -H cmd -H 5
在命令行上给出
Namespace(H='5', sp='cmd')
我希望能有类似的东西
Namespace(H=True, sp={'cmd':Namespace(h='5')})
是否有一种本地方式可以获得这样的功能,或者我是否必须经历构建自定义 argparser 的麻烦?谢谢!
Is there a native way to get something like this functionality, or do I have to go through the trouble of building a custom argparser? Thanks!
推荐答案
我想你的问题在这里得到了解答:
I think your question is answered here:
我的一个答案使用了自定义操作.
One of my answers uses a custom action.
但是处理重复参数名称的一种更简单的方法是提供一个或两个不同的dest"值.无需额外的机器即可区分两者.
But a simpler way of handling duplicate argument names, is to give one, or both, different 'dest' values. It distinguishes between the two without extra machinery.
argparser = argparse.ArgumentParser()
argparser.add_argument("-H", action="store_true")
subparser = argparser.add_subparsers(dest='sp')
cmd = subparser.add_parser("cmd")
cmd.add_argument("-H", dest='cmd_H')
print argparser.parse_args()
这篇关于嵌套参数解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!