因为之前做一个需求,遇到需要大量使用子命令( sub-command )和命令行自动生成的功能,现有的库都不能良好的满足需求,所以自己写了这个库。
如果有以下业务场景,你大概是这个库的目标用户:)
click
装饰器不会影响原有的函数调用CRUD
REST-API 的命令行调用click
的装饰器写命令行["docker", "run"]
这样的方式来添加命令six
argument type
且可拓展项目请戳 https://github.com/winkidney/cmdtree
请轻拍:)
pip install cmdtree
from cmdtree import INT
from cmdtree import command, argument, option
@argument("host", help="server listen address")
@option("reload", is_flag=True, help="if auto-reload on")
@option("port", help="server port", type=INT, default=8888)
@command(help="run a http server on given address")
def run_server(host, reload, port):
print(
"Your server running on {host}:{port}, auto-reload is {reload}".format(
host=host,
port=port,
reload=reload
)
)
if __name__ == "__main__":
from cmdtree import entry
entry()
Get help
➜ examples git:(master) python command.py --help
usage: command.py [-h] {run_server} ...
positional arguments:
{run_server} sub-commands
run_server
optional arguments:
-h, --help show this help message and exit
Run command
➜ examples git:(master) python command.py run_server localhost
Your server running on localhost:8888, auto-reload is False
Code here:
from cmdtree import group, argument, entry
@group("docker")
@argument("ip")
def docker():
pass
# nested command
@docker.command("run")
@argument("container-name")
def run(ip, container_name):
print(
"container [{name}] on host [{ip}]".format(
ip=ip,
name=container_name,
)
)
# nested command group
@docker.group("image")
def image():
pass
@image.command("create")
@argument("name")
def image_create(ip, name):
print(
"iamge {name} on {ip} created.".format(
ip=ip,
name=name,
)
)
if __name__ == "__main__":
entry()
Run command:
➜ examples git:(master) python command_group.py docker localhost image create your-docker
iamge your-docker on localhost created.