click quickstart

创建一个命令

使用command()装饰后,方法就会成为命令行

import click

@click.command()
def hello():
    click.echo('Hello World!') # 使用echo是为了统一 python2 和 python3 的print,另外还可以添加颜色属性

该方法被转换为一个命令

if __name__ == '__main__':
    hello()

在命令行中可以调用

$ python hello.py
Hello World!

还可以打印相关的信息

$ python hello.py --help
Usage: hello.py [OPTIONS]

Options:
  --help  Show this message and exit.

嵌套命令

通过group来实现命令的嵌套,将initdbdropdb放在cli命令下

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

@click.command()
def initdb():
    click.echo('Initialized the database')

@click.command()
def dropdb():
    click.echo('Dropped the database')

cli.add_command(initdb)
cli.add_command(dropdb)

还有一种方法,可以省略add_command()

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

添加参数

@click.command()
@click.option('--count', default=1, help='number of greetings')
@click.argument('name')
def hello(count, name):
    for x in range(count):
        click.echo('Hello %s!' % name)

$ python hello.py --help
Usage: hello.py [OPTIONS] NAME

Options:
  --count INTEGER  number of greetings
  --help           Show this message and exit.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章