[CmdTree] 又一个 Python 命令行库

2016-08-30 17:59:41 +08:00
 winkidney

CMDTree

因为之前做一个需求,遇到需要大量使用子命令( sub-command )和命令行自动生成的功能,现有的库都不能良好的满足需求,所以自己写了这个库。

如果有以下业务场景,你大概是这个库的目标用户:)

特性

项目请戳 https://github.com/winkidney/cmdtree

请轻拍:)


CMDTree

安装

pip install cmdtree

Quick Start

Hello world

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

SubCommand of SubCommand

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.
2726 次点击
所在节点    Python
3 条回复
Yinz
2016-08-30 23:29:01 +08:00
酷,论装饰器的一百种用法:D
winkidney
2016-08-31 09:53:53 +08:00
@Yinz 23333 总不是装饰器,爆炸……
gucheen
2016-09-01 21:42:40 +08:00
Cool!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/302731

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX