| 1 |
# Options Shortcut Decorators |
| 2 |
|
| 3 |
```{currentmodule} click |
| 4 |
``` |
| 5 |
|
| 6 |
For convenience commonly used combinations of options arguments are available as their own decorators. |
| 7 |
|
| 8 |
```{contents} |
| 9 |
--- |
| 10 |
depth: 2 |
| 11 |
local: true |
| 12 |
--- |
| 13 |
``` |
| 14 |
|
| 15 |
## Password Option |
| 16 |
|
| 17 |
Click supports hidden prompts and asking for confirmation. This is useful for password input: |
| 18 |
|
| 19 |
```{eval-rst} |
| 20 |
.. click:example:: |
| 21 |
|
| 22 |
import codecs |
| 23 |
|
| 24 |
@click.command() |
| 25 |
@click.option( |
| 26 |
"--password", prompt=True, hide_input=True, |
| 27 |
confirmation_prompt=True |
| 28 |
) |
| 29 |
def encode(password): |
| 30 |
click.echo(f"encoded: {codecs.encode(password, 'rot13')}") |
| 31 |
|
| 32 |
.. click:run:: |
| 33 |
|
| 34 |
invoke(encode, input=['secret', 'secret']) |
| 35 |
``` |
| 36 |
|
| 37 |
Because this combination of parameters is quite common, this can also be |
| 38 |
replaced with the {func}`password_option` decorator: |
| 39 |
|
| 40 |
```python |
| 41 |
@click.command() |
| 42 |
@click.password_option() |
| 43 |
def encrypt(password): |
| 44 |
click.echo(f"encoded: to {codecs.encode(password, 'rot13')}") |
| 45 |
``` |
| 46 |
|
| 47 |
## Confirmation Option |
| 48 |
|
| 49 |
For dangerous operations, it's very useful to be able to ask a user for confirmation. This can be done by adding a |
| 50 |
boolean `--yes` flag and asking for confirmation if the user did not provide it and to fail in a callback: |
| 51 |
|
| 52 |
```{eval-rst} |
| 53 |
.. click:example:: |
| 54 |
|
| 55 |
def abort_if_false(ctx, param, value): |
| 56 |
if not value: |
| 57 |
ctx.abort() |
| 58 |
|
| 59 |
@click.command() |
| 60 |
@click.option('--yes', is_flag=True, callback=abort_if_false, |
| 61 |
expose_value=False, |
| 62 |
prompt='Are you sure you want to drop the db?') |
| 63 |
def dropdb(): |
| 64 |
click.echo('Dropped all tables!') |
| 65 |
|
| 66 |
And what it looks like on the command line: |
| 67 |
|
| 68 |
.. click:run:: |
| 69 |
|
| 70 |
invoke(dropdb, input=['n']) |
| 71 |
invoke(dropdb, args=['--yes']) |
| 72 |
|
| 73 |
Because this combination of parameters is quite common, this can also be |
| 74 |
replaced with the :func:`confirmation_option` decorator: |
| 75 |
|
| 76 |
.. click:example:: |
| 77 |
|
| 78 |
@click.command() |
| 79 |
@click.confirmation_option(prompt='Are you sure you want to drop the db?') |
| 80 |
def dropdb(): |
| 81 |
click.echo('Dropped all tables!') |
| 82 |
``` |
| 83 |
|
| 84 |
## Version Option |
| 85 |
|
| 86 |
{func}`version_option` adds a `--version` option which immediately prints the version number and exits the program. |