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.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章