因为之前做一个需求,遇到需要大量使用子命令( 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.
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.