快速创建cli接口

mach.p的Python项目详细描述


https://readthedocs.org/projects/mach/badge/?version=latesthttps://travis-ci.org/oz123/mach.svg?branch=masterhttps://coveralls.io/repos/github/oz123/mach/badge.svg?branch=master

神奇的argparse命令助手

https://raw.githubusercontent.com/oz123/mach/master/imgs/mach-logo.jpg

功能

  • Get your CLI interfaces quickly
  • Turn a simple class to a CLI application or an interactive interpreter.

给定:

classCalculator:defadd(self,a,b):"""adds two numbers and prints the result"""returna+bdefdiv(self,a,b):"""divide one number by the other"""returna/b

您可以使用decoratormach1

frommachimportmach1@mach1()classCalculator:defadd(self,int:a,int:b):"""adds two numbers and prints the result"""print(a+b)defdiv(self,int:a,int:b):"""divide one number by the other"""print(a/b)calc=Calculator()calc.run()

现在,如果运行该模块,您将得到一个可以使用 标志-h--help

$ python calc.py -h
usage: calc.py [-h]{add,div} ...

positional arguments:
{add,div}   commands

   add       adds two numbers and prints the result
   div       divide one number by the other

optional arguments:
  -h, --help  show this help message and exit

每个方法都是一个子命令,带有类型检查,并且有自己的帮助。 Hench,这样不行:

$ python calc.py add foo bar
usage: calc.py add [-h] b a
calc.py add: error: argument b: invalid int value: 'foo'

这将:

$ python calc.py add 4913

要查看子命令的帮助,请使用-h

$ python calc.py add -h
usage: calc.py add [-h] b a

positional arguments:
 b
 a

optional arguments:
  -h, --help  show this help message and exit

在decoratormach2的帮助下,您可以将类转换为cli 应用程序,还有一个实用的shell,它在没有 参数如下:

$ ./examples/calc2.py
Welcome to the calc shell. Type help or ? to list commands.

calc2 > ?

Documented commands (typehelp <topic>):
========================================
add  div  exithelp

calc2 > help add
adds two numbers and prints the result
calc2 > add 246
calc2 > div 623.0
calc2 > exit
Come back soon ...
$

安装

你可以使用pip从pypi获得马赫数:

$ pip install mach.py

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java绘制两个重叠图像   java如何将图像放入源文件夹并在Eclipse中使用   java性能调优:com。麦克亨格。v2。资源库。Basicresourcepool。waitAvailable()方法占用应用程序的大部分运行时间   当分数的平行值为某个数字或更高时,java将传递的元素设置为true?   无法在java中使用SimpleFileVisitor删除某些文件。尼奥。文件   java从KType中检索注释   hadoop设置作业。java代码中的属性文件来启动oozie操作   java无响应jbutton请求并发性   java停止当前线程,直到调用的线程完成,然后继续它   JList的java大小调整问题?   通过web浏览器运行java小程序时引发异常   java如何处理selenium webdriver自动化上的背靠背警报   java处理函数只会冻结程序   截击中getparams中的java开关盒   用于显示的java getter   java如何在将布局更改为不可见时修复ClassNotFoundException