Click是一个Python用来快速实现命令行应用程序的包,主要优势表现在以下三点:
任意嵌套命令
自动生成帮助页
自动运行时lazy加载子命令
示例程序:
import [email protected]()@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=3Your 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 [email protected]()def hello(): click.echo("Hello World!")if __name__ == '__main__': hello()
输出结果:
$ python hello.pyHello 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 [email protected]()def cli(): [email protected]()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 --helpUsage: hello.py [OPTIONS] NAMEOptions: --count INTEGER number of greetings --help Show this message and exit.
继承setuptools
點擊查看更多內容
為 TA 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦