是否有用于执行 gem/git-style 命令行参数的 Python 模块?我所说的 gem/git 风格是:
$ ./MyApp.py
The most commonly used MyApp commands are:
add Add file contents to the index
bisect Find by binary search the change that introduced a bug
branch List, create, or delete branches
checkout Checkout a branch or paths to the working tree
...
$ ./MyApp.py branch
* current-branch
master
没有参数,输出告诉你如何继续。还有一个特殊的“帮助”命令:
$ ./MyApp.py help branch
这将为您提供有关“分支”命令的更深入提示。
编辑: 做我的意思是它会为您打印使用情况,以无效输入退出,根据您的 CLI 规范运行您的函数。类似于命令行的“URL 映射器”。
最佳答案
是的, argparse
与 add_subparsers()
.
这一切都在Sub-commands 中得到了很好的解释。部分。
从那里复制其中一个示例:
>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers()
>>> checkout = subparsers.add_parser('checkout', aliases=['co'])
>>> checkout.add_argument('foo')
>>> parser.parse_args(['checkout', 'bar'])
Namespace(foo='bar')
编辑:不幸的是,没有自生成的特殊 help
命令,但您可以使用 -h
获得详细的帮助消息(您似乎想要的)或 --help
就像通常在命令之后一样:
$ ./MyApp.py branch --help
我所说的冗长并不是说它就像一个手册页,它就像其他所有 --help
一种帮助:列出所有参数等...
例子:
>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers(description='Sub description')
>>> checkout = subparsers.add_parser('checkout', description='Checkout description')
>>> checkout.add_argument('foo', help='This is the foo help')
>>> parser.parse_args(['checkout', '--help'])
usage: checkout [-h] foo
Checkout description
positional arguments:
foo This is the foo help
optional arguments:
-h, --help show this help message and exit
如果需要,实现 help
应该很容易。重定向到 --help
的命令.
关于python - Python 中的 gem/git 风格的命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9729919/