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
Provenance
- Commit
2014b8d- Tree
1f7ef18- Author
Edward G <edward.g2013@gmail.com>- Committer
Edward G <edward.g2013@gmail.com>- Parent
8fcf9b0
4 files changed+249 added−297 removed
modified:docs/advanced.rst+102 added
5 unmodified lines6 In addition to common functionality that is implemented in the library7 itself, there are countless patterns that can be implemented by extending8 Click. This page should give some insight into what can be accomplished.9 10+.. contents::11+ :depth: 212+ :local:13 14+Callbacks and Eager Options15+---------------------------16+17+Sometimes, you want a parameter to completely change the execution flow.18+For instance, this is the case when you want to have a ``--version``19+parameter that prints out the version and then exits the application.20+21+Note: an actual implementation of a ``--version`` parameter that is22+reusable is available in Click as :func:`click.version_option`. The code23+here is merely an example of how to implement such a flag.24+25+In such cases, you need two concepts: eager parameters and a callback. An26+eager parameter is a parameter that is handled before others, and a27+callback is what executes after the parameter is handled. The eagerness28+is necessary so that an earlier required parameter does not produce an29+error message. For instance, if ``--version`` was not eager and a30+parameter ``--foo`` was required and defined before, you would need to31+specify it for ``--version`` to work. For more information, see32+:ref:`callback-evaluation-order`.33+34+A callback is a function that is invoked with three parameters: the35+current :class:`Context`, the current :class:`Parameter`, and the value.36+The context provides some useful features such as quitting the37+application and gives access to other already processed parameters.38+39+Here's an example for a ``--version`` flag:40+41+.. click:example::42+43+ def print_version(ctx, param, value):44+ if not value or ctx.resilient_parsing:45+ return46+ click.echo('Version 1.0')47+ ctx.exit()48+49+ @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!')54+55+The `expose_value` parameter prevents the pretty pointless ``version``56+parameter from being passed to the callback. If that was not specified, a57+boolean would be passed to the `hello` script. The `resilient_parsing`58+flag is applied to the context if Click wants to parse the command line59+without any destructive behavior that would change the execution flow. In60+this case, because we would exit the program, we instead do nothing.61+62+What it looks like:63+64+.. click:run::65+66+ invoke(hello)67+ invoke(hello, args=['--version'])68+69+Callbacks for Validation70+------------------------71+72+.. versionchanged:: 2.073+74+If you want to apply custom validation logic, you can do this in the75+parameter callbacks. These callbacks can both modify values as well as76+raise errors if the validation does not work. The callback runs after77+type conversion. It is called for all sources, including prompts.78+79+In Click 1.0, you can only raise the :exc:`UsageError` but starting with80+Click 2.0, you can also raise the :exc:`BadParameter` error, which has the81+added advantage that it will automatically format the error message to82+also contain the parameter name.83+84+.. click:example::85+86+ def validate_rolls(ctx, param, value):87+ if isinstance(value, tuple):88+ return value89+90+ try:91+ rolls, _, dice = value.partition("d")92+ return int(dice), int(rolls)93+ except ValueError:94+ raise click.BadParameter("format must be 'NdM'")95+96+ @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)")104+105+.. click:run::106+107+ invoke(roll, args=["--rolls=42"])108+ println()109+ invoke(roll, args=["--rolls=2d12"])110+ println()111+ invoke(roll, input=["42", "2d12"])112+113 .. _aliases:114 115 Command Aliases116 ---------------487 unmodified linesmodified:docs/option-decorators.rst+4 added
76 unmodified lines77 @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!')81+82+Version 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 lines5 6 .. currentmodule:: click7 8 Adding options to commands can be accomplished with the :func:`option`9-decorator. Options in Click are distinct from :ref:`positional arguments <arguments>`.9+decorator. At runtime the decorator invokes the :class:`Option` class. Options in Click are distinct from :ref:`positional arguments <arguments>`.10 11 Useful and often used kwargs are:12 13 * ``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>`18 19 .. contents::20 :depth: 221 :local:182 unmodified lines204 205 invoke(log, args=[])206 invoke(log, args=['-vvv'])207 208+.. _option-boolean-flag:209+210 Boolean211 ------------------------212 213 Boolean 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 lines282 invoke(info, args=['--help'])283 284 Flag Value285 ---------------284-To 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:286+To 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:287 288 .. click:example::289 290 import sys291 292 @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 line299 300 invoke(info, args=['--help'])301 invoke(info, args=['--upper'])302 invoke(info, args=['--lower'])301-302-Feature Switches303----------------------------304-305-In addition to boolean flags, there are also feature switches. These are306-implemented by setting multiple options to the same parameter name and307-defining a flag value. Note that by providing the ``flag_value`` parameter,308-Click will implicitly set ``is_flag=True``.309-310-To set a default flag, assign a value of `True` to the flag that should be311-the default.312-313-.. click:example::314-315- import sys316-317- @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)())323-324-.. click:run::325-326- invoke(info, args=['--upper'])327- invoke(info, args=['--help'])303 invoke(info)304 305+Values from Environment Variables306+---------------------------------307+To pass in a value in from a specific environment variable use ``envvar``.308 331-.. _option-prompting:332-333-Prompting334----------335-336-In some cases, you want parameters that can be provided from the command line,337-but if not provided, ask for user input instead. This can be implemented with338-Click by defining a prompt string.339-340-Example:341-309 .. click:example::310 311 @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}!")315 349-And what it looks like:350-316 .. click:run::317 353- invoke(hello, args=['--name=John'])354- invoke(hello, input=['John'])318+ invoke(greet, env={'USERNAME': 'john'})319 356-If you are not happy with the default prompt string, you can ask for357-a different one:320+If a list is passed to ``envvar``, the first environment variable found is picked.321 322 .. click:example::323 324 @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}!")328 366-What it looks like:367-329 .. click:run::330 370- invoke(hello, input=['John'])331+ invoke(greet, env={'ALT_USERNAME': 'Bill', 'USERNAME': 'john'})332 372-It is advised that prompt not be used in conjunction with the multiple373-flag set to True. Instead, prompt in the function interactively.333+Auto Envvar Prefix334+--------------------335 375-By default, the user will be prompted for an input if one was not passed376-through the command line. To turn this behavior off, see377-:ref:`optional-value`.336+---move to context section337 379-Dynamic Defaults for Prompts380-----------------------------338 382-The ``auto_envvar_prefix`` and ``default_map`` options for the context383-allow the program to read option values from the environment or a384-configuration file. However, this overrides the prompting mechanism, so385-that the user does not get the option to change the value interactively.339+Automatically 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 subcommand340+called ``run`` taking an option called ``reload`` and the prefix is ``WEB``, then the variable is ``WEB_RUN_RELOAD``.341 387-If you want to let the user configure the default value, but still be388-prompted if the option isn't specified on the command line, you can do so389-by supplying a callable as the default value. For example, to get a default390-from the environment:391-392-.. code-block:: python393-394- import os395-396- @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}!")403-404-To describe what the default value will be, set it in ``show_default``.405-406-.. click:example::407-408- import os409-410- @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}!")418-419-.. click:run::420-421- invoke(hello, args=["--help"])422-423-424-Callbacks and Eager Options425----------------------------426-427-Sometimes, you want a parameter to completely change the execution flow.428-For instance, this is the case when you want to have a ``--version``429-parameter that prints out the version and then exits the application.430-431-Note: an actual implementation of a ``--version`` parameter that is432-reusable is available in Click as :func:`click.version_option`. The code433-here is merely an example of how to implement such a flag.434-435-In such cases, you need two concepts: eager parameters and a callback. An436-eager parameter is a parameter that is handled before others, and a437-callback is what executes after the parameter is handled. The eagerness438-is necessary so that an earlier required parameter does not produce an439-error message. For instance, if ``--version`` was not eager and a440-parameter ``--foo`` was required and defined before, you would need to441-specify it for ``--version`` to work. For more information, see442-:ref:`callback-evaluation-order`.443-444-A callback is a function that is invoked with three parameters: the445-current :class:`Context`, the current :class:`Parameter`, and the value.446-The context provides some useful features such as quitting the447-application and gives access to other already processed parameters.448-449-Here's an example for a ``--version`` flag:450-451-.. click:example::452-453- def print_version(ctx, param, value):454- if not value or ctx.resilient_parsing:455- return456- click.echo('Version 1.0')457- ctx.exit()458-459- @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!')464-465-The `expose_value` parameter prevents the pretty pointless ``version``466-parameter from being passed to the callback. If that was not specified, a467-boolean would be passed to the `hello` script. The `resilient_parsing`468-flag is applied to the context if Click wants to parse the command line469-without any destructive behavior that would change the execution flow. In470-this case, because we would exit the program, we instead do nothing.471-472-What it looks like:473-474-.. click:run::475-476- invoke(hello)477- invoke(hello, args=['--version'])478-479-Values from Environment Variables480----------------------------------481-482-A very useful feature of Click is the ability to accept parameters from483-environment variables in addition to regular parameters. This allows484-tools to be automated much easier. For instance, you might want to pass485-a configuration file with a ``--config`` parameter but also support exporting486-a ``TOOL_CONFIG=hello.cfg`` key-value pair for a nicer development487-experience.488-489-This is supported by Click in two ways. One is to automatically build490-environment variables which is supported for options only. To enable this491-feature, the ``auto_envvar_prefix`` parameter needs to be passed to the492-script that is invoked. Each command and parameter is then added as an493-uppercase underscore-separated variable. If you have a subcommand494-called ``run`` taking an option called ``reload`` and the prefix is495-``WEB``, then the variable is ``WEB_RUN_RELOAD``.496-342 Example usage:343 344 .. click:example::345 17 unmodified lines363 the parameter name, *i.e.* ``PREFIX_COMMAND_VARIABLE``. If you have a364 subcommand called ``run-server`` taking an option called ``host`` and365 the prefix is ``WEB``, then the variable is ``WEB_RUN_SERVER_HOST``.366 522-Example:523-367 .. click:example::368 369 @click.group()370 @click.option('--debug/--no-debug')13 unmodified lines384 invoke(cli, args=['greet',],385 env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},386 auto_envvar_prefix='GREETER')387 388+Multiple Options from Environment Values389+-----------------------------------------390 546-The second option is to manually pull values in from specific environment547-variables by defining the name of the environment variable on the option.548-549-Example usage:550-551-.. click:example::552-553- @click.command()554- @click.option('--username', envvar='USERNAME')555- def greet(username):556- click.echo(f"Hello {username}!")557-558- if __name__ == '__main__':559- greet()560-561-And from the command line:562-563-.. click:run::564-565- invoke(greet, env={'USERNAME': 'john'})566-567-In that case it can also be a list of different environment variables568-where the first one is picked.569-570-Multiple Values from Environment Values571----------------------------------------572-391 As options can accept multiple values, pulling in such values from392 environment variables (which are strings) is a bit more complex. The way393 Click solves this is by leaving it up to the type to customize this394 behavior. For both ``multiple`` and ``nargs`` with values other than29 unmodified lines424 425 Other Prefix Characters426 -----------------------427 610-Click can deal with alternative prefix characters other than ``-`` for611-options. This is for instance useful if you want to handle slashes as612-parameters ``/`` or something similar. Note that this is strongly613-discouraged in general because Click wants developers to stay close to614-POSIX semantics. However in certain situations this can be useful:428+Click 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.430 431 .. click:example::432 433 @click.command()434 @click.option('+w/-w')435 def chmod(w):436 click.echo(f"writable={w}")437 623- if __name__ == '__main__':624- chmod()625-626-And from the command line:627-438 .. click:run::439 440 invoke(chmod, args=['+w'])441 invoke(chmod, args=['-w'])442 633-Note that if you are using ``/`` as prefix character and you want to use a634-boolean flag you need to separate it with ``;`` instead of ``/``:443+There are special considerations for using ``/`` as prefix character, see :ref:`option-boolean-flag` for more.444 636-.. click:example::637-638- @click.command()639- @click.option('/debug;/no-debug')640- def log(debug):641- click.echo(f"debug={debug}")642-643- if __name__ == '__main__':644- log()645-646-Callbacks for Validation647-------------------------648-649-.. versionchanged:: 2.0650-651-If you want to apply custom validation logic, you can do this in the652-parameter callbacks. These callbacks can both modify values as well as653-raise errors if the validation does not work. The callback runs after654-type conversion. It is called for all sources, including prompts.655-656-In Click 1.0, you can only raise the :exc:`UsageError` but starting with657-Click 2.0, you can also raise the :exc:`BadParameter` error, which has the658-added advantage that it will automatically format the error message to659-also contain the parameter name.660-661-.. click:example::662-663- def validate_rolls(ctx, param, value):664- if isinstance(value, tuple):665- return value666-667- try:668- rolls, _, dice = value.partition("d")669- return int(dice), int(rolls)670- except ValueError:671- raise click.BadParameter("format must be 'NdM'")672-673- @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)")681-682-.. click:run::683-684- invoke(roll, args=["--rolls=42"])685- println()686- invoke(roll, args=["--rolls=2d12"])687- println()688- invoke(roll, input=["42", "2d12"])689-690-445 .. _optional-value:446 447 Optional Value448 --------------17 unmodified lines466 467 invoke(hello, args=[])468 invoke(hello, args=["--name", "Value"])469 invoke(hello, args=["--name"])716-717-If the option has ``prompt`` enabled, then setting718-``prompt_required=False`` tells Click to only show the prompt if the719-option's flag is given, instead of if the option is not provided at all.720-721-.. click:example::722-723- @click.command()724- @click.option('--name', prompt=True, prompt_required=False, default="Default")725- def hello(name):726- click.echo(f"Hello {name}!")727-728-.. click:run::729-730- invoke(hello)731- invoke(hello, args=["--name", "Value"])732- invoke(hello, args=["--name"], input="Prompt")733-734-If ``required=True``, then the option will still prompt if it is not735-given, but it will also prompt if only the flag is given.modified:docs/prompts.rst+115 added-3 removed
9 unmodified lines10 This can be accomplished with the :func:`prompt` function, which asks for11 valid input according to a type, or the :func:`confirm` function, which asks12 for confirmation (yes/no).13 14+.. contents::15+ :depth: 216+ :local:17+18+.. _option-prompting:19+20 Option Prompts21 --------------22 17-Option prompts are integrated into the option interface. See18-:ref:`option-prompting` for more information. Internally, it19-automatically calls either :func:`prompt` or :func:`confirm` as necessary.23+Option prompts are integrated into the option interface. Internally, it24+automatically calls either :func:`prompt` or :func:`confirm` as necessary. In some cases, you want parameters that can be provided from the command line,25+but if not provided, ask for user input instead. This can be implemented with26+Click by defining a prompt string.27 28+Example:29+30+.. click:example::31+32+ @click.command()33+ @click.option('--name', prompt=True)34+ def hello(name):35+ click.echo(f"Hello {name}!")36+37+And what it looks like:38+39+.. click:run::40+41+ invoke(hello, args=['--name=John'])42+ invoke(hello, input=['John'])43+44+If you are not happy with the default prompt string, you can ask for45+a different one:46+47+.. click:example::48+49+ @click.command()50+ @click.option('--name', prompt='Your name please')51+ def hello(name):52+ click.echo(f"Hello {name}!")53+54+What it looks like:55+56+.. click:run::57+58+ invoke(hello, input=['John'])59+60+It is advised that prompt not be used in conjunction with the multiple61+flag set to True. Instead, prompt in the function interactively.62+63+By default, the user will be prompted for an input if one was not passed64+through the command line. To turn this behavior off, see65+:ref:`optional-value`.66+67 Input Prompts68 -------------69 70 To manually ask for user input, you can use the :func:`prompt` function.6 unmodified lines77 provided. For instance, the following will only accept floats::78 79 value = click.prompt('Please enter a number', default=42.0)80 81+Optional Prompts82+------------------83+If the option has ``prompt`` enabled, then setting84+``prompt_required=False`` tells Click to only show the prompt if the85+option's flag is given, instead of if the option is not provided at all.86+87+.. click:example::88+89+ @click.command()90+ @click.option('--name', prompt=True, prompt_required=False, default="Default")91+ def hello(name):92+ click.echo(f"Hello {name}!")93+94+.. click:run::95+96+ invoke(hello)97+ invoke(hello, args=["--name", "Value"])98+ invoke(hello, args=["--name"], input="Prompt")99+100+If ``required=True``, then the option will still prompt if it is not101+given, but it will also prompt if only the flag is given.102+103 Confirmation Prompts104 --------------------105 106 To ask if a user wants to continue with an action, the :func:`confirm`6 unmodified lines113 There is also the option to make the function automatically abort the114 execution of the program if it does not return ``True``::115 116 click.confirm('Do you want to continue?', abort=True)117+118+Dynamic Defaults for Prompts119+----------------------------120+121+The ``auto_envvar_prefix`` and ``default_map`` options for the context122+allow the program to read option values from the environment or a123+configuration file. However, this overrides the prompting mechanism, so124+that the user does not get the option to change the value interactively.125+126+If you want to let the user configure the default value, but still be127+prompted if the option isn't specified on the command line, you can do so128+by supplying a callable as the default value. For example, to get a default129+from the environment:130+131+.. code-block:: python132+133+ import os134+135+ @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}!")142+143+To describe what the default value will be, set it in ``show_default``.144+145+.. click:example::146+147+ import os148+149+ @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}!")157+158+.. click:run::159+160+ invoke(hello, args=["--help"])