Click命令行工具包的使用

一、安装

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

pip install click

二、使用

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 setup

setup(
    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吗?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值