编程语言
首页 > 编程语言> > [971]python命令行神器之Click

[971]python命令行神器之Click

作者:互联网

文章目录

github:https://github.com/pallets/click

Click 是 Flask 的开发团队 Pallets 的另一款开源项目,它是用于快速创建命令行的第三方模块。

我们知道,Python 内置了一个 Argparse 的标准库用于创建命令行,但使用起来有些繁琐,Click 相比于 Argparse,就好比 requests 相比于 urllib

安装

pip install -U click

例子1

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 _ in range(count):
        click.echo(f"Hello, {name}!")

if __name__ == '__main__':
    hello()

结果

$ python hello.py --count=3
Your name: Click
Hello, Click!
Hello, Click!
Hello, Click!

方法功能

把上述程序的帮助信息输出

$ python hello.py --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.

其他属性描述

group方法

Click还提供了group方法,该方法可以添加多个子命令,

import click
​
​
@click.group()
def first():
    print("hello world")
​
@click.command()
@click.option("--name", help="the name")
def second(name):
    print("this is second: {}".format(name))
​
@click.command()
def third():
    print("this is third")
​
first.add_command(second)
first.add_command(third)
​
first()

调用子命令second

$ python test.py second --name hh

# 输出
hello world
this is second: hh

密码输入

# 密码输入有两种方法
import click


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

# 方法1 :hide_input 隐式输入,confirmation_prompt:再次确认
@click.command()
@click.option('-p', prompt='请输入密码', hide_input=True, confirmation_prompt=True)
def inputp(p):
    """输入密码"""
    click.echo('p is %s' % p)

# 方法2: 我试了下,传参只能是password,其他的会报错
@click.command()
@click.password_option()
def inputp2(password):
    click.echo('p is %s' % password)

db.add_command(inputp)
db.add_command(inputp2)


if __name__ == '__main__':
    db()
# 运行如下
$ python hello.py --help
$ python3 hello.py inputp
$ python3 hello.py inputp2

参考:https://zhuanlan.zhihu.com/p/68337606
https://blog.csdn.net/weixin_38278993/article/details/100052961
https://www.jianshu.com/p/f6488f10febb

标签:__,name,971,python,hello,click,--,command,Click
来源: https://blog.csdn.net/xc_zhou/article/details/116572056