Click是一个Python用来快速实现命令行应用程序的包,主要优点表如今如下三点:python
示例程序:函数
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()
执行结果:this
$ 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()
输出结果:code
$ 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异常。ip
Click 2.0还加入了ANSI colors支持,若是输出结果到文件中还会自动去处ANSI codes。get
要使用ANSI colors咱们须要colorama包配合操做:it
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.