Click

Click 是 Flask 的开发团队 Pallets 的另一款开源项目,它是用于快速创建命令行的第三方模块。

我们知道,Python 内置了一个 Argparse 的标准库用于创建命令行,但使用起来有些繁琐,Click 相比于 Argparse,就好比 requests 相比于 urllib

Click 是一个第三方库,因此,在使用之前需要先安装:

pip install click

参考文档http://click.pocoo.org/6/options/

Click 对argparse 的主要改进在易用性,使用Click 分为两个步骤:

  1. 使用 @click.command() 装饰一个函数,使之成为命令行接口;
  2. 使用 @click.option() 等装饰函数,为其添加命令行选项等。

看一下官方文档的入门例子:

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() 使函数 hello 成为命令行接口;

  • @click.option 的第一个参数指定了命令行选项的名称,可以看到,count 的默认值是 1;

  • 使用 click.echo 进行输出是为了获得更好的兼容性,因为 print 在 Python2 和 Python3 的用法有些差别。

执行情况

$ python hello.py
Your name: Ethan # 这里会显示 'Your name: '(对应代码中的 prompt),接受用户输入
Hello Ethan! $ python hello.py --help # click 帮我们自动生成了 `--help` 用法
Usage: hello.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. $ python hello.py --count 3 --name Ethan # 指定 count 和 name 的值
Hello Ethan!
Hello Ethan!
Hello Ethan! $ python hello.py --count=3 --name=Ethan # 也可以使用 `=`,和上面等价
Hello Ethan!
Hello Ethan!
Hello Ethan! $ python hello.py --name=Ethan # 没有指定 count,默认值是 1
Hello Ethan!

Group使用

Click 通过 group 来创建一个命令行组,也就是说它可以有各种参数来解决相同类别的不同问题

import click

@click.group()
def cli():
pass @click.command()
def initdb():
click.echo('Initialized the database')
····
@click.command()
def dropdb():
click.echo('Droped the database') cli.add_command(initdb)
cli.add_command(dropdb) if __name__ == "__main__":
cli()

执行情况

$ python hello.py
Usage: hello.py [OPTIONS] COMMAND [ARGS]... Options:
--help Show this message and exit. Commands:
dropdb
initdb
$ python hello.py initdb
Initialized the database
$ python hello.py dropdb
Droped the database

click.option使用

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

在上面的例子,我们看到,除了设置命令行选项的名称,我们还会指定默认值,help 说明等,option 常用的设置参数如下:

  • default: 设置命令行参数的默认值

  • help: 参数说明

  • type: 参数类型,可以是 string, int, float 等

  • prompt: 当在命令行中没有输入相应的参数时,会根据 prompt 提示用户输入

  • nargs: 指定命令行参数接收的值的个数

  • metavar:如何在帮助页面表示值

下面,我们再看看相关的例子。

指定 type

我们可以使用 type 来指定参数类型:

import click

@click.command()
@click.option('--rate', type=float, help='rate') # 指定 rate 是 float 类型
def show(rate):
click.echo('rate: %s' % rate) if __name__ == '__main__':
show()

 执行情况:

$ python click_type.py --help
Usage: click_type.py [OPTIONS] Options:
--rate FLOAT rate
--help Show this message and exit. $ python click_type.py --rate 1
rate: 1.0
$ python click_type.py --rate 0.66
rate: 0.66

可选值

在某些情况下,一个参数的值只能是某些可选的值,如果用户输入了其他值,我们应该提示用户输入正确的值。

在这种情况下,我们可以通过 click.Choice() 来限定

执行情况:

$ python click_choice.py  --help
Usage: click_choice.py [OPTIONS] Options:
--gender [man|woman]
--help Show this message and exit. $ python click_choice.py --gender boy
Usage: click_choice.py [OPTIONS] Error: Invalid value for "--gender": invalid choice: boy. (choose from man, woman) $ python click_choice.py --gender man
gender: man

多值参数

有时,一个参数需要接收多个值。option 支持设置固定长度的参数值,通过 nargs 指定。

$ python click_multi_values.py --help
Usage: click_multi_values.py [OPTIONS] Options:
--center FLOAT... center of the circle
--radius FLOAT radius of the circle $ python click_multi_values.py --center 3 4 --radius 10
center: (3.0, 4.0), radius: 10.0 $ python click_multi_values.py --center 3 4 5 --radius 10
Usage: click_multi_values.py [OPTIONS] Error: Got unexpected extra argument (5)

输入密码

有时,在输入密码的时候,我们希望能隐藏显示。option 提供了两个参数来设置密码的输入:

hide_input 和 confirmation_promt,其中,hide_input 用于隐藏输入,confirmation_promt 用于重复输入。

import click

@click.command()
@click.option('--password', prompt=True, hide_input=True, confirmation_prompt=True)
def input_password(password):
click.echo('password: %s' % password) if __name__ == '__main__':
input_password()

执行情况:

$ python click_password.py
Password: # 不会显示密码
Repeat for confirmation: # 重复一遍
password: 123

click 也提供了一种快捷的方式,通过使用 @click.password_option(),上面的代码可以简写成:

import click

@click.command()
@click.password_option()
def input_password(password):
click.echo('password: %s' % password) if __name__ == '__main__':
input_password()

 click.IntRange()

@click.command()
@click.option('--count', type=click.IntRange(0, 20, clamp=True))
@click.option('--digit', type=click.IntRange(0, 10))
def repeat(count, digit):
click.echo(str(digit) * count) if __name__ == '__main__':
repeat() =========================================
$ repeat --count=1000 --digit=5
55555555555555555555
$ repeat --count=1000 --digit=12
Usage: repeat [OPTIONS] Error: Invalid value for "--digit": 12 is not in the valid range of 0 to 10.

改变命令行程序的执行

有些参数会改变命令行程序的执行,比如在终端输入 python 是进入 python 控制台,

而输入 python --version 是打印 python 版本。Click 提供 eager 标识对参数名进行标识,

如果输入该参数,则会拦截既定的命令行执行流程,跳转去执行一个回调函数。

import click
def print_version(ctx, param, value):
if not value or ctx.resilient_parsing:
return
click.echo('Version 1.0')
ctx.exit()
@click.command()
@click.option('--version', is_flag=True, callback=print_version,
expose_value=False, is_eager=True)
@click.option('--name', default='Ethan', help='name')
def hello(name):
click.echo('Hello %s!' % name)
if __name__ == '__main__':
hello()

其中:

  • is_eager=True 表明该命令行选项优先级高于其他选项;
  • expose_value=False 表示如果没有输入该命令行选项,会执行既定的命令行流程;
  • callback 指定了输入该命令行选项时,要跳转执行的函数
  • is_flag=True 表明参数值可以省略

执行情况:

$ python click_eager.py
Hello Ethan!
$ python click_eager.py --version # 拦截既定的命令行执行流程
Version 1.0
$ python click_eager.py --name Michael
Hello Michael!
$ python click_eager.py --version --name Ethan # 忽略 name 选项
Version 1.0

使用argument

我们除了使用 @click.option 来添加可选参数,还会经常使用 @click.argument 来添加固定参数。

它的使用和 option 类似,但支持的功能比 option 少。

入门使用

下面是一个简单的例子:

import click
@click.command()
@click.argument('coordinates')
def show(coordinates):
click.echo('coordinates: %s' % coordinates)
if __name__ == '__main__':
show()

看看执行情况:

$ python click_argument.py                     # 错误,缺少参数 coordinates
Usage: click_argument.py [OPTIONS] COORDINATES
Error: Missing argument "coordinates".
$ python click_argument.py --help # argument 指定的参数在 help 中没有显示
Usage: click_argument.py [OPTIONS] COORDINATES
Options:
--help Show this message and exit.
$ python click_argument.py --coordinates 10 # 错误用法,这是 option 参数的用法
Error: no such option: --coordinates
$ python click_argument.py 10 # 正确,直接输入值即可
coordinates: 10

多个 argument

import click
@click.command()
@click.argument('x')
@click.argument('y')
@click.argument('z')
def show(x, y, z):
click.echo('x: %s, y: %s, z:%s' % (x, y, z))
if __name__ == '__main__':
show()

执行情况

$ python click_argument.py 10 20 30
x: 10, y: 20, z:30
$ python click_argument.py 10
Usage: click_argument.py [OPTIONS] X Y Z
Error: Missing argument "y".
$ python click_argument.py 10 20
Usage: click_argument.py [OPTIONS] X Y Z
Error: Missing argument "z".
$ python click_argument.py 10 20 30 40
Usage: click_argument.py [OPTIONS] X Y Z
Error: Got unexpected extra argument (40)

不定参数

argument 还有另外一种常见的用法,就是接收不定量的参数,让我们看看例子:

import click
@click.command()
@click.argument('src', nargs=-1)
@click.argument('dst', nargs=1)
def move(src, dst):
click.echo('move %s to %s' % (src, dst))
if __name__ == '__main__':
move()

其中,nargs=-1 表明参数 src 接收不定量的参数值,参数值会以 tuple 的形式传入函数。

如果 nargs 大于等于 1,表示接收 nargs 个参数值,上面的例子中,dst 接收一个参数值。

执行情况:

$ python click_argument.py file1 trash    # src=('file1',)  dst='trash'
move ('file1',) to trash
$ python click_argument.py file1 file2 file3 trash # src=('file1', 'file2', 'file3') dst='trash'
move ('file1', 'file2', 'file3') to trash

Click 支持通过文件名参数对文件进行操作,click.File() 装饰器就是处理这种操作的,尤其是在类 Unix 系统下,它支持以 - 符号作为标准输入/输出

# File
@click.command()
@click.argument('input', type=click.File('rb'))
@click.argument('output', type=click.File('wb'))
def inout(input, output):
  while True:
    chunk = input.read(1024)
    if not chunk:
      break
    output.write(chunk)

彩色输出

在前面的例子中,我们使用 click.echo 进行输出,如果配合 colorama 这个模块,

我们可以使用 click.secho 进行彩色输出,在使用之前,使用 pip 安装 colorama:

$ pip install colorama

 例子:

import click
@click.command()
@click.option('--name', help='The person to greet.')
def hello(name):
click.secho('Hello %s!' % name, fg='red', underline=True)
click.secho('Hello %s!' % name, fg='yellow', bg='black')
if __name__ == '__main__':
hello()

其中:

  • fg 表示前景颜色(即字体颜色),可选值有:BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE 等;
  • bg 表示背景颜色,可选值有:BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE 等;
  • underline 表示下划线,可选的样式还有:dim=Truebold=True 等;

Click 通过 click.option() 添加可选参数,通过 click.argument() 来添加有可能可选的参数

以下几点是两个的区别:

  • 需要提示补全输入的时候使用 option()
  • 标志位(flag or acts) 使用 option()
  • option的值可以从环境变量获取,而argument不行
  • option的值会在帮助里面列出,而argument不能

安装打包

Click 支持使用 setuptools 来更好的实现命令行程序打包,把源码文件打包成系统中的可执行程序,

并且不限平台。一般我们会在源码根目录下创建 setup.py 脚本,先看一段简单的打包代码

from setuptools import setup

setup(
name='hello',
version='0.1',
py_modules=['hello'],
install_requires=[
'Click',
],
entry_points={'console_scripts': [
'digest=hello:digest',
'goodbye=hello:goodbye'
]},
)

hello.py

默认情况下click不提供-h。需要使用context_settings参数来重写默认help_option_names。

import click

CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])

def greeter(**kwargs):
output = '{0}, {1}!'.format(kwargs['greeting'],
kwargs['name'])
if kwargs['caps']:
output = output.upper()
print(output) @click.group(context_settings=CONTEXT_SETTINGS)
@click.version_option(version='1.0.0')
def greet():
pass @greet.command()
@click.argument('name')
@click.option('--greeting', default='Hello', help='word to use for the greeting')
@click.option('--caps', is_flag=True, help='uppercase the output')
def hello(**kwargs):
greeter(**kwargs) @greet.command()
@click.argument('name')
@click.option('--greeting', default='Goodbye', help='word to use for the greeting')
@click.option('--caps', is_flag=True, help='uppercase the output')
def goodbye(**kwargs):
greeter(**kwargs) @greet.command()
@click.option('--hash-type', type=click.Choice(['md5', 'sha1']))
def digest(hash_type):
click.echo(hash_type) if __name__ == '__main__':
greet()

 执行情况

#python hello.py install
# digest --hash-type md5
md5 # goodbye --help
Usage: goodbye [OPTIONS] NAME Options:
--greeting TEXT word to use for the greeting
--caps uppercase the output
--help Show this message and exit.
# goodbye --caps hh
GOODBYE, HH!

举例说明

import click

CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])

@click.group(context_settings=CONTEXT_SETTINGS)
@click.version_option(version='1.0.0')
def cli():
"""Repo is a command line tool that showcases how to build complex
command line interfaces with Click.
This tool is supposed to look like a distributed version control
system to show how something like this can be structured.
)"""
pass @cli.command()
@click.argument('name', default='all', required=True)
# @click.option('--greeting', default='Hello', help='word to use for the greeting')
# @click.option('--caps', is_flag=True, help='uppercase the output')
def hellocmd(name):
click.echo(
click.style(
'I am colored %s and bold' %
name,
fg='green',
bold=True)) @cli.command()
@click.option('-t', default='a', required=True,
type=click.Choice(['a', 'h']), prompt=True, help='检查磁盘空间,a表示所有空间,h表示空间大于50%')
def dfcmd(t):
"""
检查磁盘空间 dfcmd
:param t:
:return:
"""
click.echo(click.style('检查磁盘空间', fg='green', bold=True)) @cli.command(context_settings=CONTEXT_SETTINGS)
@click.argument('x', type=int, required=True)
def square(x):
"""
得到x平方 square x
"""
click.echo(click.style('x= %s' % x, fg='green', bold=True))
print(x * x) if __name__ == '__main__':
cli()

  

输出结果

XXXPycharmProjects\LuffyFTP\utils>python arg_example.py
Usage: arg_example.py [OPTIONS] COMMAND [ARGS]... Repo is a command line tool that showcases how to build complex
command line interfaces with Click. This tool is supposed to look like
a distributed version control system to show how something like this
can be structured. ) Options:
--version Show the version and exit.
-h, --help Show this message and exit. Commands:
dfcmd 检查磁盘空间 dfcmd :param t: :return:
hellocmd
square 得到x平方 square x XXXPycharmProjects\LuffyFTP\utils>python arg_example.py -h
Usage: arg_example.py [OPTIONS] COMMAND [ARGS]... Repo is a command line tool that showcases how to build complex
command line interfaces with Click. This tool is supposed to look like
a distributed version control system to show how something like this
can be structured. ) Options:
--version Show the version and exit.
-h, --help Show this message and exit. Commands:
dfcmd 检查磁盘空间 dfcmd :param t: :return:
hellocmd
square 得到x平方 square x XXXPycharmProjects\LuffyFTP\utils>python arg_example.py dfcmd -h
Usage: arg_example.py dfcmd [OPTIONS] 检查磁盘空间 dfcmd :param t: :return: Options:
-t [a|h] 检查磁盘空间,a表示所有空间,h表示空间大于50% [required]
-h, --help Show this message and exit. XXXPycharmProjects\LuffyFTP\utils>python arg_example.py square -h Usage: arg_example.py square [OPTIONS] X 得到x平方 square x Options:
-h, --help Show this message and exit. XXXPycharmProjects\LuffyFTP\utils>python arg_example.py square 5
x5
25 XXXPycharmProjects\LuffyFTP\utils>python arg_example.py square 5
x= 5
25

  

Python--Click的更多相关文章

  1. Python Click 学习笔记(转)

    原文链接:Python Click 学习笔记 Click 是 Flask 的团队 pallets 开发的优秀开源项目,它为命令行工具的开发封装了大量方法,使开发者只需要专注于功能实现.恰好我最近在开发 ...

  2. python click module for command line interface

    Click Module(一)                                                  ----xiaojikuaipao The following mat ...

  3. click python cli 开发包

    python click 包是一个方便的cli 开发包,我们可以用来开发强大的cli 应用 使用venv 进行环境准备,示例代码来自官方 venv 环境准备 python3 -m venv demoa ...

  4. K-Means clusternig example with Python and Scikit-learn(推荐)

    https://www.pythonprogramming.net/flat-clustering-machine-learning-python-scikit-learn/ Unsupervised ...

  5. Awesome Python

    Awesome Python  A curated list of awesome Python frameworks, libraries, software and resources. Insp ...

  6. Python开源框架、库、软件和资源大集合

    A curated list of awesome Python frameworks, libraries, software and resources. Inspired by awesome- ...

  7. Python 库汇总英文版

    Awesome Python  A curated list of awesome Python frameworks, libraries, software and resources. Insp ...

  8. 爬虫1.6-selenium+HeadlessChrome

    目录 爬虫-selenium+HeadlessChrome 1. 浏览器处理步骤 2. headless-chrome初体验 3. 实战爬取淘宝镇.街道信息 爬虫-selenium+HeadlessC ...

  9. web中的CSS、Xpath等路径定位方法学习

    今天不到八点就到公司了,来的比较早,趁着有点时间,总结下web中的CSS.Xpath等路径定位定位的方式吧! 简单的介绍下xpath和css的定位 理论知识就不罗列了 还是利用博客园的首页.直接附上代 ...

  10. selenium学习笔记(xpath和css定位)

    简单的介绍下xpath和css的定位 理论知识就不罗列了 还是利用博客园的首页.直接附上代码: 这个是xpath #!/usr/bin/env python # -*- coding: utf_8 - ...

随机推荐

  1. Redis在linux上的配置

    一.安装gcc  1.Redis在linux上的安装首先必须先安装gcc,这个是用来编译redis的源文件的.首先需要先切换的到root用户 2.然后开始安装gcc: yum install gcc- ...

  2. mysql修改密码方法

    1. 修改密码有三种方法:1.1 ---->用mysqladmin修改密码格式:mysqladmin -u用户名 -p旧密码 password 新密码 例子:# mysqladmin -uroo ...

  3. Python中import, from...import,import...as的区别

    import datetime print(datetime.datetime.now()) 以上代码实现输出系统当前时间,是引入整个datetime包,然后再调用datetime这个类中的now() ...

  4. Apache无法正常启动(配置多个监听端口)

    Apache监测多个端口配置: 1.conf->extra->httpd-vhosts.conf  检查配置项是否写错 2.http.conf listen端口是否监听正确 3.环境变量中 ...

  5. Android 面试问答

    Android 面试问答 目录 数据结构和算法 java核心知识 Android核心知识 架构 设计相关问题 相关工具和技术 Android 测试驱动开发 其他 数据结构和算法 ******关于此类问 ...

  6. dfs | Security Badges

    Description You are in charge of the security for a large building, with n rooms and m doors between ...

  7. PHP开发——变量

    变量的概念 l  变量是临时存储数据的容器: l  变量是存储内存当中: l  我们现实中有很多数据:姓名.性别.年龄.学历等: l  在计算机中,用变量来代替一个一个的数据: l  我们可以把计算机 ...

  8. 探索未知种族之osg类生物---呼吸分解之渲染遍历二

    那么今天我们就正式进入osg整个呼吸动作之中最复杂的一个动作,ViewerBase::renderingTraversals(),我们先介绍renderingTraversals的开头的简单的几步操作 ...

  9. 第二阶段第二次spring会议

    昨天我对39个组发表了建议以及总结了改进意见和改进方案. 今天我对便签加上了清空回收站功能 private void 清空回收站ToolStripMenuItem_Click(object sende ...

  10. python环境问题(pycharm)

    一.问题 我们在使用python的时候会遇到环境配置问题.如何可以一劳永逸,是我们解决问题的基本思想. 二.解决1.新建环境: 2.添加环境:选择需要的环境,可以是conda,亦可以是virtual. ...