选项装饰¶
为了方便起见,常用的选项参数组合可以作为它们自己的装饰器。
密码选项¶
Click支持隐藏提示和请求确认。 这对于密码输入很有用:
import codecs
@click.command()
@click.option(
"--password", prompt=True, hide_input=True,
confirmation_prompt=True
)
def encode(password):
click.echo(f"encoded: {codecs.encode(password, 'rot13')}")
$ encode
Password:
Repeat for confirmation:
encoded: frperg
由于这种参数组合非常常见,因此也可以用 password_option()
装饰师:
@click.command()
@click.password_option()
def encrypt(password):
click.echo(f"encoded: to {codecs.encode(password, 'rot13')}")
确认选项¶
对于危险操作,能够询问用户确认非常有用。 这可以通过添加布尔值来完成 --yes
标志,如果用户没有提供它,则要求确认,并在回调中失败:
def abort_if_false(ctx, param, value):
if not value:
ctx.abort()
@click.command()
@click.option('--yes', is_flag=True, callback=abort_if_false,
expose_value=False,
prompt='Are you sure you want to drop the db?')
def dropdb():
click.echo('Dropped all tables!')
以及它在命令行上的样子:
$ dropdb
Are you sure you want to drop the db? [y/N]: n
Aborted!
$ dropdb --yes
Dropped all tables!
由于这种参数组合非常常见,因此也可以用 confirmation_option()
装饰师:
@click.command()
@click.confirmation_option(prompt='Are you sure you want to drop the db?')
def dropdb():
click.echo('Dropped all tables!')
版本选项¶
version_option()
新增了一项 --version
选项,该选项立即打印版本号并退出程序。