跳转到主要内容

快速创建CLI接口

项目描述

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

魔法Argparse命令助手

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

特性

  • 快速获得CLI接口

  • 将简单类转换为CLI应用程序或交互式解释器。

给定

class Calculator:

    def add(self, a, b):
        """adds two numbers and prints the result"""
        return a + b

    def div(self, a, b):
        """divide one number by the other"""
        return a / b

您可以使用装饰器mach1创建命令行应用程序

from mach import mach1

@mach1()
class Calculator:

    def add(self, int: a, int: b):
        """adds two numbers and prints the result"""
       print(a + b)

    def div(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

每个方法都是一个子命令,具有类型检查和非常有用的帮助。因此,这将不起作用

$ 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 4 9
13

要查看子命令的帮助,请使用-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

使用装饰器mach2的帮助,您可以转换您的类为CLI应用程序,并且还有一个交互式外壳,在没有参数的情况下调用

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

calc2 > ?

Documented commands (type help <topic>):
========================================
add  div  exit  help

calc2 > help add
adds two numbers and prints the result
calc2 > add 2 4
6
calc2 > div 6 2
3.0
calc2 > exit
Come back soon ...
$

安装

您可以使用pip从PyPI获取mach

$ pip install mach.py

项目详情


下载文件

下载适用于您的平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源分布

mach.py-0.4.4.tar.gz (78.7 kB 查看散列值)

上传时间: 源代码

支持者