开放的编程资料库

当前位置:我爱分享网 > Python教程 > 正文

Python 使用 theclick

Pythonclick教程展示了如何使用theclick模块创建命令行界面。

Python点击

Pythonclick模块用于创建命令行(CLI)应用程序。它是标准optparse和argparse模块的易于使用的替代品。它允许任意嵌套命令,自动生成帮助页面,并支持在运行时延迟加载子命令。

click模块是作为Flaskweb框架的支持库创建的。

命令是应用程序的基本构建块。单击通过装饰器定义命令。它们是使用click.command装饰器创建的。值通过选项或参数传递给命令。使用click.option装饰器添加选项,使用click.argument添加参数。选项中的值遵循选项的名称,而参数则按位置获取。

$ pip install -U click

我们安装了click模块。对于彩色输出,我们还需要colorama模块。

Python点击简单例子

以下是一个简单的CLI示例。

import click

@click.command()
def hello():
    click.echo('Hello there')


if __name__ == '__main__':
    hello()

该示例创建了一个输出消息的命令。

@click.command()
def hello():
    click.echo('Hello there')

Click使用echo而不是print。它增加了兼容性并添加了着色支持。

$ ./simple.py 
Hello there
$ ./simple.py --help
Usage: simple.py [OPTIONS]

Options:
  --help  Show this message and exit.

点击创建一些开箱即用的帮助消息。

Python点击默认参数

参数是用click.argument装饰器添加的。参数可能有默认值。

#!/usr/bin/python

import click


@click.command()
@click.argument('name', default='guest')
def hello(name):
    click.echo(f'Hello {name}')

 
if __name__ == '__main__':
    hello()

该示例使用给定的参数值构建一条消息。如果没有参数,则使用默认来宾。参数作为变量传递给函数。

$ ./argument.py Peter
Hello Peter
$ ./argument.py 
Hello guest

我们在有参数和没有参数的情况下运行程序。

Python点击​​参数类型

我们可以指定参数类型,包括int、float、str、bool、choice和各种范围。默认为str。

#!/usr/bin/python

import click


@click.command()
@click.argument('name', default='guest')
@click.argument('age', type=int)
def hello(name, age):
    click.echo(f'{name} is {age} years old')

 
if __name__ == '__main__':
    hello()

在示例中,我们有两个参数:姓名和年龄。它们是按位置生成的,第一个是名字,第二个是年龄。

$ ./argument_type.py Peter 34
Peter is 34 years old

Python点击​​可变数量的参数

使用nargs选项,我们可以设置一个参数采用多个值。对于-1值,参数可以采用可变数量的值。

#!/usr/bin/python

import click
from operator import mul
from functools import reduce

@click.command()
@click.argument('vals', type=int, nargs=-1)
def process(vals):

    print(f'The sum is {sum(vals)}')
    print(f'The product is {reduce(mul, vals, 1)}')


if __name__ == '__main__':
    process()

该示例创建了一个process命令,它可以在vals参数中采用可变数量的整数值。该命令计算值的总和和乘积。

$ ./variable_args.py 1 2 3 4 5
The sum is 15
The product is 120

Python点击简单选项

使用click.option装饰器将选项添加到命令。选项名称以一或两个破折号为前缀。

#!/usr/bin/python

import click


@click.command()
@click.option('--n', type=int, default=1)
def dots(n):
    click.echo('.' * n)


if __name__ == '__main__':
    dots()

在这个例子中,我们有一个接受数字的--n选项。该数字决定了将点打印到控制台的次数。

$ ./dots.py --n 17
.................

我们输出了十七个点。

Python点击​​选项名称

选项名称以一个破折号或两个破折号开头。命令行程序通常同时采用短选项和长选项。如果同时使用了长名称,则Click从长名称派生选项的名称。

#!/usr/bin/python

import click


@click.command()
@click.option('-s', '--string')
def output(string):
    click.echo(string)


if __name__ == '__main__':
    output()

在示例中,我们创建了一个具有短名称和长名称的选项。传递给函数的变量名称是string,派生自较长的选项名称。

$ ./option_names.py -s sky
sky
$ ./option_names.py --string cloud
cloud

我们使用两个选项名称运行程序。

Python点击值提示

我们可以要求用户以交互方式提供一个值。

#!/usr/bin/python

import click

@click.command()
@click.option("--name", prompt="Your name", help="Provide your name")
def hello(name):
    click.echo(f"Hello, {name}")

if __name__ == '__main__':
    hello()

该示例询问用户他的姓名。

$ ./prompt.py 
Your name: Peter
Hello, Peter

这是一个示例输出。

Python点击颜色输出

使用secho方法,我们可以输出彩色文本。我们还可以使用粗体和下划线等样式。颜色值限于一组预定义的值。对于颜色输出,我们需要安装colorama模块。

#!/usr/bin/python

import click


@click.command()
def coloured():
    click.secho('Hello there', fg="blue", bold=True)


if __name__ == '__main__':
    coloured()

该示例以粗体蓝色输出文本。

Python点击​​标志

标志是可以启用或禁用的布尔选项。这可以通过一次定义两个标志来实现,两个标志由斜线(/)分隔,用于启用或禁用该选项或使用is_flag参数。

#!/usr/bin/python

import click


@click.command()
@click.option('--blue', is_flag=True, help='message in blue color')
def hello(blue):

    if blue:
        click.secho('Hello there', fg='blue')
    else:
        click.secho('Hello there')

 
if __name__ == '__main__':
    hello()

在示例中,我们使用is_flag参数定义了一个--blue布尔选项。如果设置,它将以蓝色打印消息。

#!/usr/bin/python

import click


@click.command()
@click.argument('word')
@click.option('--shout/--no-shout', default=False)
def output(word, shout):
    if shout:
        click.echo(word.upper())
    else:
        click.echo(word)

if __name__ == '__main__':
    output()

在第二种情况下,我们定义了--shout--no-shout标志。如果设置了--shout标志,则指定的参数以大写形式输出。

$ ./flags2.py --shout sky
SKY
$ ./flags2.py --no-shout sky
sky

Python点击环境变量

可以从环境变量中提取值。

#!/usr/bin/python

import click
import os

@click.argument('mydir', envvar='MYDIR', type=click.Path(exists=True))
@click.command()
def dolist(mydir):

    click.echo(os.listdir(mydir))


if __name__ == '__main__':
    dolist()

该示例打印在MYDIR环境变量中指定的目录的内容。

export MYDIR=~/Documents; ./env_var.py 
['test.py', 'words2.txt', 'test.php', 'words2.txt~', 'testing', 'todo.txt', 
'tasks', 'links.txt', 'progs']

这是一个示例输出。

Python点击​​选项元组

我们可以拥有成为Python元组的多值选项。

#!/usr/bin/python

import click


@click.command()
@click.option('--data', required=True, type=(str, int))
def output(data):
    click.echo(f'name={data[0]} age={data[1]}')


if __name__ == '__main__':
    output()

在示例中,--data选项采用两个值,这两个值成为Python元组。这些值用于构建消息。

$ ./multi_val.py --data Peter 23
name=Peter age=23

这是一个示例输出。

多次指定选项

选项值可以多次提供并记录所有值。这些值存储在Python元组中。

#!/usr/bin/python

import click


@click.command()
@click.option('--word', '-w', multiple=True)
def words(word):
    click.echo('\n'.join(word))

if __name__ == '__main__':
    words()

在示例中,我们可以多次指定--word/-w选项。

$ ./multiples.py -w sky --word forest --word rock -w cloud
sky
forest
rock
cloud

这是一个示例输出。

点击文件类型

click.File类型将参数声明为用于读取或写入的文件。一旦上下文中断(命令完成工作后),该文件将自动关闭。

sky
cloud
water
forest
rock
moon
falcon
lake

我们使用这个文本文件。

#!/usr/bin/python

import click

@click.command()
@click.argument('file_name', type=click.File('r'))
@click.argument('lines', default=-1, type=int)
def head(file_name, lines):

    counter = 0

    for line in file_name:

        print(line.strip())
        counter += 1

        if counter == lines: 
            break


if __name__ == '__main__':
    head()

我们创建了一个等同于Linuxhead命令的命令。

$ ./head.py words.txt 4
sky
cloud
water
forest

我们显示文件的前四行。

点击路径类型

click.Path类型类似于click.File类型。它不返回打开的文件句柄,而是只返回文件名。

#!/usr/bin/python

import click

@click.command()
@click.argument('file_name', type=click.Path(exists=True))
@click.argument('lines', default=-1, type=int)
def head(file_name, lines):

    with open(file_name, 'r') as f:

        counter = 0

        for line in file_name:

            print(line.strip())
            counter += 1

            if counter == lines: 
                break


if __name__ == '__main__':
    head()

这是使用click.Path类型创建的head命令。

Python点击​​命令组

可以将命令添加到组中。组是使用@click.group装饰器创建的。

#!/usr/bin/python

import click


@click.group()
def messages():
  pass


@click.command()
def generic():
    click.echo('Hello there')


@click.command()
def welcome():
    click.echo('Welcome')


messages.add_command(generic)
messages.add_command(welcome)


if __name__ == '__main__':
    messages()

该示例定义了两个组。

$ ./groups.py --help
Usage: groups.py [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

Commands:
  generic
  welcome

帮助消息显示了两个命令。

#!/usr/bin/python

import click


@click.group()
def cli():
  pass


@cli.command(name='gen')
def generic():
    click.echo('Hello there')


@cli.command(name='wel')
def welcome():
    click.echo('Welcome')


if __name__ == '__main__':
    cli()

这是创建命令组的另一种语法。这些命令采用函数的名称,但可以使用name选项指定另一个名称。

$ ./groups2.py gen
Hello there
$ ./groups2.py wel
Welcome

在本教程中,我们使用了Pythonclick模块。

列出所有Python教程。

未经允许不得转载:我爱分享网 » Python 使用 theclick

感觉很棒!可以赞赏支持我哟~

赞(0) 打赏