1. 介绍
click是python第三方库,用于快速创建命令行。运行代码相关的github地址为:https://github.com/DeathGodBXX/test_click_module
2. 典型使用形式
下面是一种最简单的使用形式
import click
@click.command() # 装饰func函数,使之成为命令行接口;
@click.option('--param', default=default_value, help='description') # 添加命令行选项
def func(param):
pass
3. 简单的例子
下面这个例子是对greeting函数增加参数,--count(the count of greetings), --name(the name of greetings)
import click
# 装饰函数greeting,使其成为命令行接口
@click.command()
# 添加 --count 参数
@click.option('--count', default=1, help='the count of greetings')
# 添加 --name 参数
@click.option('--name', prompt='your name', help='the name of greetings')
def greeting(count, name):
for i in range(count):
click.echo('Hello, %s' %name)
if __name__ == '__main__':
greeting()
执行结果如下:
option通过指定命令行选项名称,从命令行读取参数值,传递给函数,option常用的设置参数如下:
default | 设置命令行参数的默认值 |
help | 参数的帮助说明 |
type | 指定参数类型,可以是常用的string,int,float等,也可以是列表等 |
prompt | 当在命令行没有输入参数,进行提示 |
nargs | 指定传参的个数 |
4. click.Choice()
使用click.Choice()可以指定某以参数的可选值
import click
@click.command()
@click.option('--gender', type=click.Choice(['man', 'woman']), help='the gender of the person')
def person(gender):
click.echo('gender=%s' % gender)
if __name__ == '__main__':
person()
运行结果如下:
4. 隐士输入密码和验证
hide_input用于隐式输入密码,comfirmation_promt用于隐藏密码输入
import click
@click.command()
@click.option('--password', prompt='please enter the password', hide_input=True, confirmation_promt=True)
def input_passwd(password):
click.echo('password=%s' % password)
if __name__ == '__main__':
input_passwd()
运行结果如下:
常用的click用法就给大家分享到这里,如有问题欢迎讨论交流!