创建python cli应用程序几乎不费吹灰之力!
mando的Python项目详细描述
mando是argparse的包装器,允许您编写完整的cli 应用在几秒钟内,同时保持所有的灵活性。
安装
mando在从python 2.6到python的所有python版本中进行测试。 3.6以及pypy上。您可以使用pip安装它:
$ pip install mando
问题
而argparse对于只有 一个,默认命令,当您必须添加多个命令并管理它们时 事情变得非常混乱和漫长。但别担心,曼多来帮忙了!
快速启动
frommandoimportcommand,main@commanddefecho(text,capitalize=False):ifcapitalize:text=text.upper()print(text)if__name__=='__main__':main()
生成的帮助:
$ python example.py -h usage: example.py [-h] {echo} ... positional arguments: {echo} echo Echo the given text. optional arguments: -h, --help show this help message and exit $ python example.py echo -h usage: example.py echo [-h] [--capitalize] text Echo the given text. positional arguments: text optional arguments: -h, --help show this help message and exit --capitalize
实际使用量:
$ python example.py echo spam spam $ python example.py echo --capitalize spam SPAM
一个real示例
更复杂和真实的东西-ish。代码:
frommandoimportcommand,main@commanddefpush(repository,all=False,dry_run=False,force=False,thin=False):'''Update remote refs along with associated objects. :param repository: Repository to push to. :param --all: Push all refs. :param -n, --dry-run: Dry run. :param -f, --force: Force updates. :param --thin: Use thin pack.'''print('Pushing to {0}. All: {1}, dry run: {2}, force: {3}, thin: {4}'.format(repository,all,dry_run,force,thin))if__name__=='__main__':main()
mando理解docstring中的sphinx样式:param:,因此它创建 做空期权及其对你的帮助。
$ python git.py push -h usage: git.py push [-h] [--all] [-n] [-f] [--thin] repository Update remote refs along with associated objects. positional arguments: repository Repository to push to. optional arguments: -h, --help show this help message and exit --all Push all refs. -n, --dry-run Dry run. -f, --force Force updates. --thin Use thin pack.
我们试试看!
$ python git.py push --all myrepo Pushing to myrepo. All: True, dry run: False, force: False, thin: False $ python git.py push --all -f myrepo Pushing to myrepo. All: True, dry run: False, force: True, thin: False $ python git.py push --all -fn myrepo Pushing to myrepo. All: True, dry run: True, force: True, thin: False $ python git.py push --thin -fn myrepo Pushing to myrepo. All: False, dry run: True, force: True, thin: True $ python git.py push --thin usage: git.py push [-h] [--all] [-n] [-f] [--thin] repository git.py push: error: too few arguments
惊讶啊?是的,曼多得到了看空期权和docstring的帮助! 你可以在docstring中添加更多内容,如果这还不够,那么 @argdecorator自定义传递给argparse的参数。
曼多还有很多其他选择。例如,它支持不同的docstring Sties(Sphinx、Google和Numpy)支持通过 argcomplete包并支持自定义格式类。完全 文档,访问https://mando.readthedocs.org/。