創建一個命令
使用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.