Click: 命令行工具神器

Click是一个Python用来快速实现命令行应用程序的包,主要优势表现在以下三点:

  • 任意嵌套命令
  • 自动生成帮助页
  • 自动运行时lazy加载子命令

示例程序:

import click

@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name', help='The person to greet.')
def hello(count, name):
"""Simple program that greets NAME for a total of COUNT times."""
for x in range(count):
click.echo('Hello %s!' % name)

if name == 'main':
hello()

执行结果:

$ python hello.py --count=3
Your name: John
Hello John!
Hello John!
Hello John!

它还会自动生成格式化好的帮助信息:

$ python hello.py --help
Usage: hello.py [OPTIONS]

Simple program that greets NAME for a total of COUNT times.

Options:
--count INTEGER Number of greetings.
--name TEXT The person to greet.
--help Show this message and exit.

快速入门

安装

pip install Click

创建一个命令

通过装时器函数click.command()来注册命令

import click

@click.command()
def hello():
click.echo("Hello World!")

if name == 'main':
hello()

输出结果:

$ python hello.py
Hello World!

相应的帮助页:

$ python hello.py --help
Usage: hello.py [OPTIONS]

Options:
--help Show this message and exit.

输出

为什么不用print,还要加入一个echo呢。Click尝试用一个兼容Python 2和Python 3相同方式来处理。也防止了一些终端编码不一致出现UnicodeError异常。

Click 2.0还加入了ANSI colors支持,如果输出结果到文件中还会自动去处ANSI codes。

要使用ANSI colors我们需要colorama包配合操作:

pipenv install colorama

示例:
click.echo(click.style("Hello World!", fg='green')) # click.secho('Hello World!', fg='green')

嵌套命令

import click

@click.group()
def cli():
pass

@cli.command()
def initdb():
click.echo('Initialized the database')

@cli.command()
def dropdb():
click.echo('Dropped the database')

if name == 'main':
cli()

添加参数

使用option()和argument()装饰器增加参数

@click.command()
@click.option('--count', default=1, help='number of greetings')
@click.argument('name')
def hello(count, name):
for x in range(count):
click.echo('Hello %s!' % name)
What it looks like:

$ python hello.py --help
Usage: hello.py [OPTIONS] NAME

Options:
--count INTEGER number of greetings
--help Show this message and exit.

继承setuptools

查看详情

posted @ 2018-12-05 12:03  疯人院主任  阅读(988)  评论(0)    收藏  举报