python click模块用于编写命令行程序,它的目的是使用更少的代码,加快编写CLI程序的速度。
pip install click
click提供以下三个功能:
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.