欢迎订阅我的YouTube频道,https://www.youtube.com/c/xugaoxiang

Python实用模块(一)click

Python实用模块 xugaoxiang

软硬件环境

  • ubuntu 18.04 64bit
  • anaconda with python 3.6
  • click

click模块

click是一个创建命令行接口的第三方python库,是Command Line Interface Creation Kit的缩写。click具有高度可配置、代码量更少、代码更加优雅等特点。是argparse的升级版。

安装click

pip install 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()

@click.command()表示在某个方法上接收命令行参数,@click.option表示跟的具体参数,一个参数接一个@click.option--count跟方法hello里的第一个参数名count保持一致。

运行上面程序,输出

xugaoxiang@ubuntu:~/Downloads$ python click_demo.py 
Your name: xugaoxiang
Hello xugaoxiang!

xugaoxiang@ubuntu:~/Downloads$ python click_demo.py --count 5
Your name: xugaoxiang
Hello xugaoxiang!
Hello xugaoxiang!
Hello xugaoxiang!
Hello xugaoxiang!
Hello xugaoxiang!

xugaoxiang@ubuntu:~/Downloads$ python click_demo.py --count 5 --name xgx
Hello xgx!
Hello xgx!
Hello xgx!
Hello xgx!
Hello xgx!

可以通过的--help来查看具体的参数情况

xugaoxiang@ubuntu:~/Downloads$ python click_demo.py --help
Usage: click_demo.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.

参考资料

喜欢 (0)