> 文章列表 > Click命令行工具包的使用

Click命令行工具包的使用

Click命令行工具包的使用

一、安装

官方文档:Welcome to Click — Click Documentation (8.1.x)

pip install clicke

二、使用

1、最简单的方式

import click@click.command()
def hello():click.echo('Hello World!') # 自带的echo比print更强,可以处理颜色、编码、异常等等if __name__ == '__main__':hello()

使用:

(venv) bocai@bogon crontab % python hello.py
Hello World!

2、命令组合的方式

# 初级-命令组合
@click.group()
def cli():pass@cli.command()
def initdb():click.echo('Initialized the database')@cli.command()
def dropdb():click.echo('Dropped the database')if __name__ == '__main__':cli()

使用:

(venv) bocai@bogon crontab % python tasks.py 
Usage: tasks.py [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

Commands:
  dropdb
  initdb
(venv) bocai@bogon crontab % python tasks.py dropdb
Dropped the database

3、添加参数

import click@click.command()
@click.option('--count', default=1, type=click.INT, help='number of greetings')
@click.argument('name')
def hello(count, name):for x in range(count):click.echo(f"Hello {name}!")

option的type参数支持str、int、float、bool、choice、uuid、file、path、datetime等,还可自定义

其他参数可以参考官方文档

使用:

(venv) bocai@bogon crontab % python tasks.py --help
Usage: tasks.py [OPTIONS] NAME

Options:
  --count INTEGER  number of greetings
  --help           Show this message and exit.

(venv) bocai@bogon crontab % python tasks.py --count 2 老王   
Hello 老王!
Hello 老王!

提示:

多数情况下,我们使用option代替argument,option有更灵活的使用方式,如参数自动提示、值可以从环境变量提取、在--help下自动显示等。

argument更被推荐用在执行子命令(如上面的python tasks.py dropdb)、参数为文件路径或者URL的情况,否则使用option更合适。

三、setuptools打包你的命令

在tasks.py同级目录下创建setup.py文件,内容如下:

from setuptools import setupsetup(name='say_hello',version='0.1.0',py_modules=['tasks'],install_requires=['Click',],entry_points={'console_scripts': ['hello_boy = tasks:hello',],},
)

然后,在当前目录下执行如下命令:

# 打包,会自动生成say_hello-0.1.0.tar.gz文件
$ python setup.py sdist
# 安装
$ pip install say_hello-0.1.0.tar.gz   或
$ easy_install say_hello-0.1.0.tar.gz

更详细打包命令可以参考你真的了解python中的setup.py吗?