创建一个命令
使用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
来实现命令的嵌套,将initdb
和dropdb
放在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.