快速创建cli接口
mach.p的Python项目详细描述
神奇的argparse命令助手
功能
- 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