Click是一个Python包,用于以可组合的方式创建漂亮的命令行界面,只需要很少的代码。这是“命令行界面创建工具包”。它具有高度可配置性,但具有开箱即用的合理默认值。
安装:
pip install click
简单的使用步骤:
@click.command() 装饰一个函数,使之成为命令行接口;
@click.option() 装饰函数,为其添加命令行选项等。
官方示例
# 此文件名为hello.py
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()
在上面的例子中,函数hello接受两个参数,分别是count和name,他们的取值从命令行中获取,这里我们使用了click模块中的command、option、echo,他们的作用如下:
command:使函数hello成为命令行接口
option:增加命令行选项
echo:输出结果,使用echo进行输出是为了更好的兼容性,因为python 2中的print是个语句,python 3中的print 是一个函数
运行上面的脚本,可以通过命令指定--name,--count的值,由于我们在option中指定了prompt选项,那么如果我们执行脚本没有传递name这个参数时,Click会提示我们在交互模式下输入。
运行时的样子:
$ python hello.py --count=3
Your name: John
Hello John!
Hello John!
Hello John!
它会自动生成格式良好的帮助页面:
$ python hello.py --help
Usage: hello [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.
option最基本的用法就是通过指定命令行选项的名称,从命令行读取参数值,再将其传递给函数。option常用的参数含义:
import click @click.command() @click.option(‘--desc‘, nargs=2, type=str) # nargs确定参数个数,变量值会以tuple形式传入函数 def hello(desc): click.echo(‘Hello %s %s‘ % desc) if __name__ == ‘__main__‘: hello() # 执行 python hello.py --desc "帅哥" "xx" # 结果 (‘帅哥‘, ‘xx‘) Hello 帅哥 xx
import click @click.command() @click.option(‘--sex‘, required=True, type=click.Choice([‘male‘, ‘female‘]), prompt=‘你的性别‘) # 限定-c的值为start,或者stop,required表示是否为必填参数 def set_sex(sex): click.echo(‘你的性别是%s‘ % sex) if __name__ == ‘__main__‘: set_sex() # 1.输入参数 python test.py --sex male 你的性别是male # 2.不输入参数 python test.py 你的性别 (male, female): male 你的性别是male
原文:https://www.cnblogs.com/Zzbj/p/11309130.html