Click

作者: 飞行睿客 | 来源:发表于2020-04-05 19:14 被阅读0次

一、说明

Click 是一个命令行管理包,可以通过更少的代码量和更多的组合方式创建出各种命令行,具有高度可配置和开箱即用的默认设置。

二、安装

pip install click

三、简单命令

  • 官方给出的 Demo,创建 hello.py 文件
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()
  • 执行 click 命令
python hello.py --count=3
  • 帮助文档
$ 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.

四、 选项 option

  1. 多个值的选项,通过参数 nargs 配置
@click.command()
@click.option('--pos', nargs=2, type=float)
def findme(pos):
    click.echo('%s / %s' % pos)

执行命令

$ findme --pos 2.0 3.0 2.0 / 3.0
  1. 和 nargs 类似,有时候可能会需要一个参数传递多次,同时记录每次的值而不是只记录最后一个值。 比如,git commit -m foo -m bar 会记录两行 commit 信息:foo 和 bar。这个功能 可以通过 multiple 参数实现:
@click.command()
@click.option('--message', '-m', multiple=True)
def commit(message):
    click.echo('\n'.join(message))

执行命令

$ commit -m foo -m bar
foo
bar
  1. 计数
@click.command()
@click.option('-v', '--verbose', count=True)
def log(verbose):
    click.echo('Verbosity: %s' % verbose)

执行命令

$ log -vvv Verbosity: 3
  1. **布尔值标记
import sys

@click.command()
@click.option('--shout/--no-shout', default=False)
def info(shout):
    rv = sys.platform
    if shout:
        rv = rv.upper() + '!!!!111'
    click.echo(rv)

执行命令

$ info --shout
LINUX2!!!!111
$ info --no-shout
linux2
  1. 选择选项,有时候你想要一个值为某个列表内的某一个的参数。这种情况下,你可以使用 Choice 类型。它可以实例化一个包含有效值的列表。
@click.command()
@click.option('--hash-type', type=click.Choice(['md5', 'sha1']))
def type_choice(hash_type):
    click.echo(hash_type)

执行命令

$ type-choice --hash-type=md5
md5

$ type-choice --hash-type=foo
Usage: type-choice [OPTIONS]

Error: Invalid value for "--hash-type": invalid choice: foo. (choose from md5, sha1)

$ type-choice --help
Usage: type-choice [OPTIONS]

Options:
  --hash-type [md5|sha1]
  --help                  Show this message and exit.

九、参考文档

https://click.palletsprojects.com/en/5.x/

https://click-docs-zh-cn.readthedocs.io/zh/latest/index.html

https://hustyichi.github.io/2019/03/19/click/

https://juejin.im/post/5ddbe004f265da7e040c9828#heading-1

https://www.jianshu.com/p/572251c91dd0

https://www.cnblogs.com/xiao-apple36/p/9089027.html#_label2_2

相关文章

网友评论

      本文标题:Click

      本文链接:https://www.haomeiwen.com/subject/odfpphtx.html