软硬件环境
- 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.