ITPub博客

首页 > 数据库 > 数据库开发技术 > Python命令行库:Click 简易教程

Python命令行库:Click 简易教程

原创 数据库开发技术 作者:五分钟学SRE 时间:2021-12-05 22:14:45 0 删除 编辑

Click 是 Python 下一款命令行库,可以用来快速轻松实现Python命令行程序。

Click 被设计用来快速构建命令行程序,因此缺乏一些扩展性,比如他不允许高度定制help介绍。Click 是用来支持 Flask 开发框架的。

click安装

pip3 install click
click组件介绍

click.command()

脚本里的函数被click.command()装饰以后,函数就变成了一个命令行工具

hello_click

import click
@click.command()def hello(): click.echo("hello five-m-sre!")

if __name__ == '__main__': hello()

运行

装饰器 click.command() 使函数变成命令行工具,echo 函数的作用等同于 print 函数。

python3 hello_click.py hello five-m-sre!

click.option()

装饰器 click.option()可以给命令行函数指定参数

  • --count:count是参数的名字

  • default :参数的默认值

  • type:给参数指定类型

  • help:说明文档

执行脚本的时候后面加上参数 --help 就可以查看说明文档。

示例1:Hello five-m-python

import click
@click.command()@click.option("-name",default="file-m-python!",help="title",type=str)def hello(name): # click.echo("hello five-m-sre!") click.echo("hello {name}".format(name=name))

if __name__ == '__main__': hello()

运行

只用click, 很轻松的就传递了参数,不仅如此,还提供了查看文档的功能,执行命令,在脚本的后面使用--help参数,就可以获得命令行工具的说明文档

python3 hello_click.py hello file-m-python!
//--helppython3 hello_click.py --helpUsage: hello_click.py [OPTIONS]
Options: -name TEXT title --help Show this message and exit.
示例2:
import click
@click.command()@click.option("-name",default="file-m-python!",help="title",type=str)@click.option("--count",default=1,help="print count",type=int)def hello(count,name): # click.echo("hello five-m-sre!") for i in range(count): click.echo("hello {name}".format(name=name))

if __name__ == '__main__': hello()

运行

python3 hello_click.py -name "hello five-m sre" --count 3hello hello five-m srehello hello five-m srehello hello five-m sre

click.argument()

有些命令行工具在运行的时候要求用户输入信息,可以给 option 装饰器指定 prompt 参数

示例:

import click
@click.command()# @click.option("-name",default="file-m-python!",help="title",type=str)@click.option("--count",default=1,help="print count",type=int)@click.argument("name")def hello(count,name): # click.echo("hello five-m-sre!") for i in range(count): click.echo("hello {name}".format(name=name))

if __name__ == '__main__': hello()
可以先使用--help查看下工具文档,可以看到name变成一个必须传输的参数
python3 hello_click.py --helpUsage: hello_click.py [OPTIONS] NAME
Options: --count INTEGER print count --help Show this message and exit.

运行

 
python3 hello_click.py --count=2 "five-m-python"hello five-m-pythonhello five-m-python


click.group()

click.group()可以让我们把许多命令加到一个组中,为了解藕,我们会将不同的逻辑进行分类,加到不同功能的组

示例:

import click
@click.group() #命令总入口def cli(): pass
@cli.command() # cli 表示该方法属于@click.group@click.option("--name",default="five-m-python!",help="group1",type=str) #传参仍然使用click。而不是clidef hello_group1(name): """ group1: name ([str]): [print name] """ click.echo("hello {}".format(name))
@cli.command()@click.option("--count",default=1,help="group2 count")@click.argument("name")def hello_group2(count,name): """ group2: count ([int]): [print count] name ([str]): [print name] """ for i in range(count): print("hello {}".format(name))

if __name__ == '__main__': # hello() cli() #这里调用cli(),而不是调用子命令s

运行:

@click.group 装饰器把函数装饰成为一个Group对象,通过 Group 可以添加很多子命令。

python3 hello_click.py --helpUsage: hello_click.py [OPTIONS] COMMAND [ARGS]...
Options: --help Show this message and exit.
Commands: hello-group1 group1: name ([str]): [print name] hello-group2 group2: count ([int]): [print count] name ([str]): [print...
python3 hello_click.py hello-group1 hello five-m-python!
python3 hello_click.py hello-group2 --count=3 "five-m-sre"hello five-m-srehello five-m-srehello five-m-sre

打包跨平台可执行程序

通过 Click 编写了简单的命令行方法后,还需要把 .py 文件转换成可以在控制台里运行的命令行程序。Click 支持使用 setuptools 来更好的实现命令行程序打包,把源码文件打包成系统中的可执行程序,并且不限平台。一般我们会在源码根目录下创建 setup.py 脚本,先看一段简单的打包代码:

from setuptools import setup
setup( name='hello-five-m-sre', version='0.1', py_modules=['hello-sre'], install_requires=[ 'Click', ], entry_points=''' [console_scripts] hello-sre=hello_click:cli ''',)
tip:
  • name 就是包的名字

  • version 指定了版本

  • py_modules 指定了模块名称

  • entry_points 设置成[console_scripts], 表明要安装成可以在终端调用的命令模块,

  • cooldb=demo:cli,cooldb是命令,执行该命令时,等同于执行demo.py的cli

使用pip进行打包安装

pip install --editable .
Obtaining file:///Users/ops/pythonRequirement already satisfied: Click in /usr/local/lib/python3.7/site-packages (from hello-five-m-sre==0.1) (8.0.3)Requirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/site-packages (from Click->hello-five-m-sre==0.1) (3.4.0)Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/site-packages (from importlib-metadata->Click->hello-five-m-sre==0.1) (3.6.0)Requirement already satisfied: typing-extensions>=3.6.4 in /usr/local/lib/python3.7/site-packages (from importlib-metadata->Click->hello-five-m-sre==0.1) (3.10.0.2)Installing collected packages: hello-five-m-sre Running setup.py develop for hello-five-m-sreSuccessfully installed hello-five-m-sre-0.1

Successfully 表示安装成功,现在,就可以像使用pip命令一样使用cooldb命令了

hello-sre --helpUsage: hello-sre [OPTIONS] COMMAND [ARGS]...
Options: --help Show this message and exit.
Commands: hello-group1 group1: name ([str]): [print name] hello-group2 group2: count ([int]): [print count] name ([str]): [print... hello-sre hello-group1hello five-m-python!



推荐博文:(Python Click 学习笔记)https://isudox.com/2016/09/03/learning-python-package-click/


click官方中文文档:https://click-docs-zh-cn.readthedocs.io/zh/latest/quickstart.html



原文作者:五分钟学SRE;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2021-11-23

  • 博文量
    81
  • 访问量
    38733