QZQ的小世界!

  • 首页
你好!
这里是QZQ的博客站!
  1. 首页
  2. 未分类
  3. 正文

Click-命令行模块

2025年4月4日 61点热度 0人点赞 0条评论

Click 是 Flask 的开发团队 Pallets 的另一款开源项目,它是用于快速创建命令行的第三方模块。
参考文档:Options — Click Documentation (8.1.x) (palletsprojects.com)

Usage

command:用于装饰一个函数,使得该函数作为命令行的接口
option:用于装饰一个函数,主要功能是为命令行添加选项
echo:用于输出结果,由于print函数在2.x和3.x之间存在不同之处,为了更好的兼容性,因此提供了echo输出方法
Choice:输入为一个列表,列表中为选项可选择的值
...

Basic Example

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()

执行情况

**$ 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!**

Function

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

Option

指定命令行选项的名称,从命令行读取参数值,再将其传递给函数,最开始的案例有涉及该函数。

常用的参数:

  • default:给命令行选项添加默认值

  • help:给命令行选项添加帮助信息

  • type:指定参数的数据类型,例如int、str、float

  • required:是否为必填选项,True为必填,False为非必填

  • prompt:在命令行提示用户输入对应选项的信息

  • nargs:指定命令行选项接收参数的个数,如果超过则会报错

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

隐藏输入

有时,在输入密码的时候,我们希望能隐藏显示
hide_input 和 confirmation_promt,其中,hide_input 用于隐藏输入,confirmation_promt 用于重复输入。

@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()

Choic

在某些情况下,一个参数的值只能是某些可选的值,如果用户输入了其他值,我们应该提示用户输入正确的值。在这种情况下,我们可以通过 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

argument

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

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**

接收多个参数

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)**

接收不定量参数

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

[文章导入自 http://qzq-go.notion.site/3c5ca8c9ec774b6aa992dfe7f918445a 访问原文获取高清图片]

本作品采用 知识共享署名-非商业性使用 4.0 国际许可协议 进行许可
标签: IT技术 Python Python库介绍 Python第三方库
最后更新:2025年4月3日

QZQ

一只涉猎广泛的技术爱好者,绝赞养猫中~

点赞
< 上一篇
下一篇 >

归档

  • 2025 年 4 月
  • 2025 年 3 月
  • 2025 年 2 月
  • 2025 年 1 月
  • 2024 年 12 月
  • 2024 年 11 月

分类

  • 技术
  • 未分类

COPYRIGHT © 2024 QZQ的小世界!. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang