Skip to content
Myr

Rewrite second half of options docs. Move some sections to other places.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Edward G · committed by Edward G · parent 8fcf9b0 · Browse files · 4 files+249 added−297 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+249 added−297 removed

  • other:+249 added−297 removed

4 files+249 added−297 removed

modified:docs/advanced.rst+102 added
5 unmodified lines
6In addition to common functionality that is implemented in the library7itself, there are countless patterns that can be implemented by extending8Click. This page should give some insight into what can be accomplished.910.. contents::11 :depth: 212 :local:1314Callbacks and Eager Options15---------------------------1617Sometimes, you want a parameter to completely change the execution flow.18For instance, this is the case when you want to have a ``--version``19parameter that prints out the version and then exits the application.2021Note: an actual implementation of a ``--version`` parameter that is22reusable is available in Click as :func:`click.version_option`. The code23here is merely an example of how to implement such a flag.2425In such cases, you need two concepts: eager parameters and a callback. An26eager parameter is a parameter that is handled before others, and a27callback is what executes after the parameter is handled. The eagerness28is necessary so that an earlier required parameter does not produce an29error message. For instance, if ``--version`` was not eager and a30parameter ``--foo`` was required and defined before, you would need to31specify it for ``--version`` to work. For more information, see32:ref:`callback-evaluation-order`.3334A callback is a function that is invoked with three parameters: the35current :class:`Context`, the current :class:`Parameter`, and the value.36The context provides some useful features such as quitting the37application and gives access to other already processed parameters.3839Here's an example for a ``--version`` flag:4041.. click:example::4243 def print_version(ctx, param, value):44 if not value or ctx.resilient_parsing:45 return46 click.echo('Version 1.0')47 ctx.exit()4849 @click.command()50 @click.option('--version', is_flag=True, callback=print_version,51 expose_value=False, is_eager=True)52 def hello():53 click.echo('Hello World!')5455The `expose_value` parameter prevents the pretty pointless ``version``56parameter from being passed to the callback. If that was not specified, a57boolean would be passed to the `hello` script. The `resilient_parsing`58flag is applied to the context if Click wants to parse the command line59without any destructive behavior that would change the execution flow. In60this case, because we would exit the program, we instead do nothing.6162What it looks like:6364.. click:run::6566 invoke(hello)67 invoke(hello, args=['--version'])6869Callbacks for Validation70------------------------7172.. versionchanged:: 2.07374If you want to apply custom validation logic, you can do this in the75parameter callbacks. These callbacks can both modify values as well as76raise errors if the validation does not work. The callback runs after77type conversion. It is called for all sources, including prompts.7879In Click 1.0, you can only raise the :exc:`UsageError` but starting with80Click 2.0, you can also raise the :exc:`BadParameter` error, which has the81added advantage that it will automatically format the error message to82also contain the parameter name.8384.. click:example::8586 def validate_rolls(ctx, param, value):87 if isinstance(value, tuple):88 return value8990 try:91 rolls, _, dice = value.partition("d")92 return int(dice), int(rolls)93 except ValueError:94 raise click.BadParameter("format must be 'NdM'")9596 @click.command()97 @click.option(98 "--rolls", type=click.UNPROCESSED, callback=validate_rolls,99 default="1d6", prompt=True,100 )101 def roll(rolls):102 sides, times = rolls103 click.echo(f"Rolling a {sides}-sided dice {times} time(s)")104105.. click:run::106107 invoke(roll, args=["--rolls=42"])108 println()109 invoke(roll, args=["--rolls=2d12"])110 println()111 invoke(roll, input=["42", "2d12"])112113.. _aliases:114115Command Aliases116---------------
487 unmodified lines
modified:docs/option-decorators.rst+4 added
76 unmodified lines
77 @click.command()78 @click.confirmation_option(prompt='Are you sure you want to drop the db?')79 def dropdb():80 click.echo('Dropped all tables!')8182Version Option83----------------84:func:`version_option` adds a --version option which immediately prints the version number and exits the program.
modified:docs/options.rst+28 added-294 removed
4 unmodified lines
56.. currentmodule:: click78Adding options to commands can be accomplished with the :func:`option`9decorator. Options in Click are distinct from :ref:`positional arguments <arguments>`.9decorator. At runtime the decorator invokes the :class:`Option` class. Options in Click are distinct from :ref:`positional arguments <arguments>`.1011Useful and often used kwargs are:1213* ``default``: Passes a default.14* ``help``: Sets help message.15* ``nargs``: Sets the number of arguments.16* ``required``: Makes option required.17* ``type``: Sets :ref:`parameter-types`17* ``type``: Sets :ref:`parameter type <parameter-types>`1819.. contents::20 :depth: 221 :local:
182 unmodified lines
204205 invoke(log, args=[])206 invoke(log, args=['-vvv'])207208.. _option-boolean-flag:209210Boolean211------------------------212213Boolean options (boolean flags) take the value True or False. The simplest case sets the default value to ``False`` if the flag is not passed, and ``True`` if it is.
68 unmodified lines
282 invoke(info, args=['--help'])283284Flag Value285---------------284To have an flag pass a value to the underlying function set ``is_flag=True`` and set ``flag_value`` to the value desired. This can be used to create patterns like this:286To have an flag pass a value to the underlying function set ``flag_value`` to the value desired. This automatically sets ``is_flag=True``. To set a default flag, set ``default=True``. Setting flag values can be used to create patterns like this:287288.. click:example::289290 import sys291292 @click.command()291 @click.option('--upper', 'transformation', flag_value='upper')293 @click.option('--upper', 'transformation', flag_value='upper', default=True)294 @click.option('--lower', 'transformation', flag_value='lower')295 def info(transformation):296 click.echo(getattr(sys.platform, transformation)())297
1 unmodified line
299300 invoke(info, args=['--help'])301 invoke(info, args=['--upper'])302 invoke(info, args=['--lower'])301302Feature Switches303---------------------------304305In addition to boolean flags, there are also feature switches. These are306implemented by setting multiple options to the same parameter name and307defining a flag value. Note that by providing the ``flag_value`` parameter,308Click will implicitly set ``is_flag=True``.309310To set a default flag, assign a value of `True` to the flag that should be311the default.312313.. click:example::314315 import sys316317 @click.command()318 @click.option('--upper', 'transformation', flag_value='upper',319 default=True)320 @click.option('--lower', 'transformation', flag_value='lower')321 def info(transformation):322 click.echo(getattr(sys.platform, transformation)())323324.. click:run::325326 invoke(info, args=['--upper'])327 invoke(info, args=['--help'])303 invoke(info)304305Values from Environment Variables306---------------------------------307To pass in a value in from a specific environment variable use ``envvar``.308331.. _option-prompting:332333Prompting334---------335336In some cases, you want parameters that can be provided from the command line,337but if not provided, ask for user input instead. This can be implemented with338Click by defining a prompt string.339340Example:341309.. click:example::310311 @click.command()345 @click.option('--name', prompt=True)346 def hello(name):347 click.echo(f"Hello {name}!")312 @click.option('--username', envvar='USERNAME')313 def greet(username):314 click.echo(f"Hello {username}!")315349And what it looks like:350316.. click:run::317353 invoke(hello, args=['--name=John'])354 invoke(hello, input=['John'])318 invoke(greet, env={'USERNAME': 'john'})319356If you are not happy with the default prompt string, you can ask for357a different one:320If a list is passed to ``envvar``, the first environment variable found is picked.321322.. click:example::323324 @click.command()362 @click.option('--name', prompt='Your name please')363 def hello(name):364 click.echo(f"Hello {name}!")325 @click.option('--username', envvar=['ALT_USERNAME', 'USERNAME'])326 def greet(username):327 click.echo(f"Hello {username}!")328366What it looks like:367329.. click:run::330370 invoke(hello, input=['John'])331 invoke(greet, env={'ALT_USERNAME': 'Bill', 'USERNAME': 'john'})332372It is advised that prompt not be used in conjunction with the multiple373flag set to True. Instead, prompt in the function interactively.333Auto Envvar Prefix334--------------------335375By default, the user will be prompted for an input if one was not passed376through the command line. To turn this behavior off, see377:ref:`optional-value`.336---move to context section337379Dynamic Defaults for Prompts380----------------------------338382The ``auto_envvar_prefix`` and ``default_map`` options for the context383allow the program to read option values from the environment or a384configuration file. However, this overrides the prompting mechanism, so385that the user does not get the option to change the value interactively.339Automatically built environment variables are supported for options only. To enable this feature, the ``auto_envvar_prefix`` parameter needs to be passed to the script that is invoked. Each command and parameter is then added as an uppercase underscore-separated variable. If you have a subcommand340called ``run`` taking an option called ``reload`` and the prefix is ``WEB``, then the variable is ``WEB_RUN_RELOAD``.341387If you want to let the user configure the default value, but still be388prompted if the option isn't specified on the command line, you can do so389by supplying a callable as the default value. For example, to get a default390from the environment:391392.. code-block:: python393394 import os395396 @click.command()397 @click.option(398 "--username", prompt=True,399 default=lambda: os.environ.get("USER", "")400 )401 def hello(username):402 click.echo(f"Hello, {username}!")403404To describe what the default value will be, set it in ``show_default``.405406.. click:example::407408 import os409410 @click.command()411 @click.option(412 "--username", prompt=True,413 default=lambda: os.environ.get("USER", ""),414 show_default="current user"415 )416 def hello(username):417 click.echo(f"Hello, {username}!")418419.. click:run::420421 invoke(hello, args=["--help"])422423424Callbacks and Eager Options425---------------------------426427Sometimes, you want a parameter to completely change the execution flow.428For instance, this is the case when you want to have a ``--version``429parameter that prints out the version and then exits the application.430431Note: an actual implementation of a ``--version`` parameter that is432reusable is available in Click as :func:`click.version_option`. The code433here is merely an example of how to implement such a flag.434435In such cases, you need two concepts: eager parameters and a callback. An436eager parameter is a parameter that is handled before others, and a437callback is what executes after the parameter is handled. The eagerness438is necessary so that an earlier required parameter does not produce an439error message. For instance, if ``--version`` was not eager and a440parameter ``--foo`` was required and defined before, you would need to441specify it for ``--version`` to work. For more information, see442:ref:`callback-evaluation-order`.443444A callback is a function that is invoked with three parameters: the445current :class:`Context`, the current :class:`Parameter`, and the value.446The context provides some useful features such as quitting the447application and gives access to other already processed parameters.448449Here's an example for a ``--version`` flag:450451.. click:example::452453 def print_version(ctx, param, value):454 if not value or ctx.resilient_parsing:455 return456 click.echo('Version 1.0')457 ctx.exit()458459 @click.command()460 @click.option('--version', is_flag=True, callback=print_version,461 expose_value=False, is_eager=True)462 def hello():463 click.echo('Hello World!')464465The `expose_value` parameter prevents the pretty pointless ``version``466parameter from being passed to the callback. If that was not specified, a467boolean would be passed to the `hello` script. The `resilient_parsing`468flag is applied to the context if Click wants to parse the command line469without any destructive behavior that would change the execution flow. In470this case, because we would exit the program, we instead do nothing.471472What it looks like:473474.. click:run::475476 invoke(hello)477 invoke(hello, args=['--version'])478479Values from Environment Variables480---------------------------------481482A very useful feature of Click is the ability to accept parameters from483environment variables in addition to regular parameters. This allows484tools to be automated much easier. For instance, you might want to pass485a configuration file with a ``--config`` parameter but also support exporting486a ``TOOL_CONFIG=hello.cfg`` key-value pair for a nicer development487experience.488489This is supported by Click in two ways. One is to automatically build490environment variables which is supported for options only. To enable this491feature, the ``auto_envvar_prefix`` parameter needs to be passed to the492script that is invoked. Each command and parameter is then added as an493uppercase underscore-separated variable. If you have a subcommand494called ``run`` taking an option called ``reload`` and the prefix is495``WEB``, then the variable is ``WEB_RUN_RELOAD``.496342Example usage:343344.. click:example::345
17 unmodified lines
363the parameter name, *i.e.* ``PREFIX_COMMAND_VARIABLE``. If you have a364subcommand called ``run-server`` taking an option called ``host`` and365the prefix is ``WEB``, then the variable is ``WEB_RUN_SERVER_HOST``.366522Example:523367.. click:example::368369 @click.group()370 @click.option('--debug/--no-debug')
13 unmodified lines
384 invoke(cli, args=['greet',],385 env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},386 auto_envvar_prefix='GREETER')387388Multiple Options from Environment Values389-----------------------------------------390546The second option is to manually pull values in from specific environment547variables by defining the name of the environment variable on the option.548549Example usage:550551.. click:example::552553 @click.command()554 @click.option('--username', envvar='USERNAME')555 def greet(username):556 click.echo(f"Hello {username}!")557558 if __name__ == '__main__':559 greet()560561And from the command line:562563.. click:run::564565 invoke(greet, env={'USERNAME': 'john'})566567In that case it can also be a list of different environment variables568where the first one is picked.569570Multiple Values from Environment Values571---------------------------------------572391As options can accept multiple values, pulling in such values from392environment variables (which are strings) is a bit more complex. The way393Click solves this is by leaving it up to the type to customize this394behavior. For both ``multiple`` and ``nargs`` with values other than
29 unmodified lines
424425Other Prefix Characters426-----------------------427610Click can deal with alternative prefix characters other than ``-`` for611options. This is for instance useful if you want to handle slashes as612parameters ``/`` or something similar. Note that this is strongly613discouraged in general because Click wants developers to stay close to614POSIX semantics. However in certain situations this can be useful:428Click can deal with prefix characters besides ``-`` for options. Click can use429``/``, ``+`` as well as others. Note that alternative prefix characters are generally used very sparingly if at all within POSIX.430431.. click:example::432433 @click.command()434 @click.option('+w/-w')435 def chmod(w):436 click.echo(f"writable={w}")437623 if __name__ == '__main__':624 chmod()625626And from the command line:627438.. click:run::439440 invoke(chmod, args=['+w'])441 invoke(chmod, args=['-w'])442633Note that if you are using ``/`` as prefix character and you want to use a634boolean flag you need to separate it with ``;`` instead of ``/``:443There are special considerations for using ``/`` as prefix character, see :ref:`option-boolean-flag` for more.444636.. click:example::637638 @click.command()639 @click.option('/debug;/no-debug')640 def log(debug):641 click.echo(f"debug={debug}")642643 if __name__ == '__main__':644 log()645646Callbacks for Validation647------------------------648649.. versionchanged:: 2.0650651If you want to apply custom validation logic, you can do this in the652parameter callbacks. These callbacks can both modify values as well as653raise errors if the validation does not work. The callback runs after654type conversion. It is called for all sources, including prompts.655656In Click 1.0, you can only raise the :exc:`UsageError` but starting with657Click 2.0, you can also raise the :exc:`BadParameter` error, which has the658added advantage that it will automatically format the error message to659also contain the parameter name.660661.. click:example::662663 def validate_rolls(ctx, param, value):664 if isinstance(value, tuple):665 return value666667 try:668 rolls, _, dice = value.partition("d")669 return int(dice), int(rolls)670 except ValueError:671 raise click.BadParameter("format must be 'NdM'")672673 @click.command()674 @click.option(675 "--rolls", type=click.UNPROCESSED, callback=validate_rolls,676 default="1d6", prompt=True,677 )678 def roll(rolls):679 sides, times = rolls680 click.echo(f"Rolling a {sides}-sided dice {times} time(s)")681682.. click:run::683684 invoke(roll, args=["--rolls=42"])685 println()686 invoke(roll, args=["--rolls=2d12"])687 println()688 invoke(roll, input=["42", "2d12"])689690445.. _optional-value:446447Optional Value448--------------
17 unmodified lines
466467 invoke(hello, args=[])468 invoke(hello, args=["--name", "Value"])469 invoke(hello, args=["--name"])716717If the option has ``prompt`` enabled, then setting718``prompt_required=False`` tells Click to only show the prompt if the719option's flag is given, instead of if the option is not provided at all.720721.. click:example::722723 @click.command()724 @click.option('--name', prompt=True, prompt_required=False, default="Default")725 def hello(name):726 click.echo(f"Hello {name}!")727728.. click:run::729730 invoke(hello)731 invoke(hello, args=["--name", "Value"])732 invoke(hello, args=["--name"], input="Prompt")733734If ``required=True``, then the option will still prompt if it is not735given, but it will also prompt if only the flag is given.
modified:docs/prompts.rst+115 added-3 removed
9 unmodified lines
10This can be accomplished with the :func:`prompt` function, which asks for11valid input according to a type, or the :func:`confirm` function, which asks12for confirmation (yes/no).1314.. contents::15 :depth: 216 :local:1718.. _option-prompting:1920Option Prompts21--------------2217Option prompts are integrated into the option interface. See18:ref:`option-prompting` for more information. Internally, it19automatically calls either :func:`prompt` or :func:`confirm` as necessary.23Option prompts are integrated into the option interface. Internally, it24automatically calls either :func:`prompt` or :func:`confirm` as necessary. In some cases, you want parameters that can be provided from the command line,25but if not provided, ask for user input instead. This can be implemented with26Click by defining a prompt string.2728Example:2930.. click:example::3132 @click.command()33 @click.option('--name', prompt=True)34 def hello(name):35 click.echo(f"Hello {name}!")3637And what it looks like:3839.. click:run::4041 invoke(hello, args=['--name=John'])42 invoke(hello, input=['John'])4344If you are not happy with the default prompt string, you can ask for45a different one:4647.. click:example::4849 @click.command()50 @click.option('--name', prompt='Your name please')51 def hello(name):52 click.echo(f"Hello {name}!")5354What it looks like:5556.. click:run::5758 invoke(hello, input=['John'])5960It is advised that prompt not be used in conjunction with the multiple61flag set to True. Instead, prompt in the function interactively.6263By default, the user will be prompted for an input if one was not passed64through the command line. To turn this behavior off, see65:ref:`optional-value`.6667Input Prompts68-------------6970To manually ask for user input, you can use the :func:`prompt` function.
6 unmodified lines
77provided. For instance, the following will only accept floats::7879 value = click.prompt('Please enter a number', default=42.0)8081Optional Prompts82------------------83If the option has ``prompt`` enabled, then setting84``prompt_required=False`` tells Click to only show the prompt if the85option's flag is given, instead of if the option is not provided at all.8687.. click:example::8889 @click.command()90 @click.option('--name', prompt=True, prompt_required=False, default="Default")91 def hello(name):92 click.echo(f"Hello {name}!")9394.. click:run::9596 invoke(hello)97 invoke(hello, args=["--name", "Value"])98 invoke(hello, args=["--name"], input="Prompt")99100If ``required=True``, then the option will still prompt if it is not101given, but it will also prompt if only the flag is given.102103Confirmation Prompts104--------------------105106To ask if a user wants to continue with an action, the :func:`confirm`
6 unmodified lines
113There is also the option to make the function automatically abort the114execution of the program if it does not return ``True``::115116 click.confirm('Do you want to continue?', abort=True)117118Dynamic Defaults for Prompts119----------------------------120121The ``auto_envvar_prefix`` and ``default_map`` options for the context122allow the program to read option values from the environment or a123configuration file. However, this overrides the prompting mechanism, so124that the user does not get the option to change the value interactively.125126If you want to let the user configure the default value, but still be127prompted if the option isn't specified on the command line, you can do so128by supplying a callable as the default value. For example, to get a default129from the environment:130131.. code-block:: python132133 import os134135 @click.command()136 @click.option(137 "--username", prompt=True,138 default=lambda: os.environ.get("USER", "")139 )140 def hello(username):141 click.echo(f"Hello, {username}!")142143To describe what the default value will be, set it in ``show_default``.144145.. click:example::146147 import os148149 @click.command()150 @click.option(151 "--username", prompt=True,152 default=lambda: os.environ.get("USER", ""),153 show_default="current user"154 )155 def hello(username):156 click.echo(f"Hello, {username}!")157158.. click:run::159160 invoke(hello, args=["--help"])