argparse 可选的子解析器(用于 --version) [英] argparse optional subparser (for --version)
本文介绍了argparse 可选的子解析器(用于 --version)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码(使用 Python 2.7):
I have the following code (using Python 2.7):
# shared command line options, like --version or --verbose
parser_shared = argparse.ArgumentParser(add_help=False)
parser_shared.add_argument('--version', action='store_true')
# the main parser, inherits from `parser_shared`
parser = argparse.ArgumentParser(description='main', parents=[parser_shared])
# several subcommands, which can't inherit from the main parser, since
# it would expect subcommands ad infinitum
subparsers = parser.add_subparsers('db', parents=[parser_shared])
...
args = parser.parse_args()
现在我希望能够调用这个程序,例如将 --version
附加到普通程序或某些子命令:
Now I would like to be able to call this program e.g. with the --version
appended to the normal program or some subcommand:
$ prog --version
0.1
$ prog db --version
0.1
基本上,我需要声明可选的子解析器.我知道这不是真正支持,但是否有任何解决方法或替代方法?
Basically, I need to declare optional subparsers. I'm aware that this isn't really supported, but are there any workarounds or alternatives?
我收到的错误消息:
$ prog db --version
# works fine
$ prog --version
usage: ....
prog: error: too few arguments
推荐答案
根据文档,--version
带有 action='version'
(而不是 action='store_true'
) 自动打印版本号:
According to documentation, --version
with action='version'
(and not with action='store_true'
) prints automatically the version number:
parser.add_argument('--version', action='version', version='%(prog)s 2.0')
这篇关于argparse 可选的子解析器(用于 --version)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文