python之Click的简单应用

时间:2019-08-06
本文章向大家介绍python之Click的简单应用,主要包括python之Click的简单应用使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、介绍

Click是一个Python包,用于以可组合的方式创建漂亮的命令行界面,只需要很少的代码。这是“命令行界面创建工具包”。它具有高度可配置性,但具有开箱即用的合理默认值。

安装:

pip install click

官方文档(7.x版本)

二、使用

简单的使用步骤:
@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.

三、其他参数

1、option的参数

option最基本的用法就是通过指定命令行选项的名称,从命令行读取参数值,再将其传递给函数。option常用的参数含义:

  • default: 设置命令行参数的默认值
  • help:参数说明
  • type:参数类型,可以是str、int、float等
  • prompt:当在命令行中没有输入相应的参数时,会更具prompt提示用户输入
  • nargs:指定命令行参数接受的值的个数
  • required:是否为必填参数
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

四、扩展用法

1、限定用户从选项列表中选择输入

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