python进阶

python click模块

2017-01-11  本文已影响92人  nummycode

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.
上一篇 下一篇

猜你喜欢

热点阅读