python - Python 中的 gem/git 风格的命令行参数

标签 python command-line-interface

是否有用于执行 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/

相关文章:

python - 具有常规属性的 SQLAlchemy DetachedInstanceError(不是关系)

python - Python 中的多线程 : Getting stuck at last thread

python - numpy数组中的元素排列

command-line-interface - 如何在 PHP CLI 版本中更改 php.ini 的路径

angular - 将 pubnub 添加到 angular2 cli 项目

php - 无法执行 exec 命令 (php/windows/ffmpeg)

php - Laravel 4.x,CLI已停止工作

python - Pandas - 当字符串匹配时选择两个值之间的所有行

python - 动态服务 django docker 容器

java - 'az account list' 的 API 等效项是什么?