Skip to content
Myr

options.rst

This file

Path

docs/options.rst

927 lines · 25.8 KiB

Last changed by

remove old upgrading notesDavid Lordbefore adoptiona327751

History of this file

Take it

1.. _options:23Options4=======56.. currentmodule:: click78Adding options to commands can be accomplished by the :func:`option`9decorator.  Since options can come in various different versions, there10are a ton of parameters to configure their behavior. Options in click are11distinct from :ref:`positional arguments <arguments>`.1213Name Your Options14-----------------1516Options have a name that will be used as the Python argument name when17calling the decorated function. This can be inferred from the option18names or given explicitly. Names are given as position arguments to the19decorator.2021A name is chosen in the following order22231.  If a name is not prefixed, it is used as the Python argument name24    and not treated as an option name on the command line.252.  If there is at least one name prefixed with two dashes, the first26    one given is used as the name.273.  The first name prefixed with one dash is used otherwise.2829To get the Python argument name, the chosen name is converted to lower30case, up to two dashes are removed as the prefix, and other dashes are31converted to underscores.3233.. code-block:: python3435    @click.command()36    @click.option('-s', '--string-to-echo')37    def echo(string_to_echo):38        click.echo(string_to_echo)3940.. code-block:: python4142    @click.command()43    @click.option('-s', '--string-to-echo', 'string')44    def echo(string):45        click.echo(string)4647-   ``"-f", "--foo-bar"``, the name is ``foo_bar``48-   ``"-x"``, the name is ``x``49-   ``"-f", "--filename", "dest"``, the name is  ``dest``50-   ``"--CamelCase"``, the name is ``camelcase``51-   ``"-f", "-fb"``, the name is ``f``52-   ``"--f", "--foo-bar"``, the name is ``f``53-   ``"---f"``, the name is ``_f``5455Basic Value Options56-------------------5758The most basic option is a value option.  These options accept one59argument which is a value.  If no type is provided, the type of the default60value is used.  If no default value is provided, the type is assumed to be61:data:`STRING`.  Unless a name is explicitly specified, the name of the62parameter is the first long option defined; otherwise the first short one is63used. By default, options are not required, however to make an option required,64simply pass in `required=True` as an argument to the decorator.6566.. click:example::6768    @click.command()69    @click.option('--n', default=1)70    def dots(n):71        click.echo('.' * n)7273.. click:example::7475    # How to make an option required76    @click.command()77    @click.option('--n', required=True, type=int)78    def dots(n):79        click.echo('.' * n)8081.. click:example::8283    # How to use a Python reserved word such as `from` as a parameter84    @click.command()85    @click.option('--from', '-f', 'from_')86    @click.option('--to', '-t')87    def reserved_param_name(from_, to):88        click.echo(f"from {from_} to {to}")8990And on the command line:9192.. click:run::9394   invoke(dots, args=['--n=2'])9596In this case the option is of type :data:`INT` because the default value97is an integer.9899To show the default values when showing command help, use ``show_default=True``100101.. click:example::102103    @click.command()104    @click.option('--n', default=1, show_default=True)105    def dots(n):106        click.echo('.' * n)107108.. click:run::109110   invoke(dots, args=['--help'])111112For single option boolean flags, the default remains hidden if the default113value is False.114115.. click:example::116117    @click.command()118    @click.option('--n', default=1, show_default=True)119    @click.option("--gr", is_flag=True, show_default=True, default=False, help="Greet the world.")120    @click.option("--br", is_flag=True, show_default=True, default=True, help="Add a thematic break")121    def dots(n, gr, br):122        if gr:123            click.echo('Hello world!')124        click.echo('.' * n)125        if br:126            click.echo('-' * n)127128.. click:run::129130   invoke(dots, args=['--help'])131132133Multi Value Options134-------------------135136Sometimes, you have options that take more than one argument.  For options,137only a fixed number of arguments is supported.  This can be configured by138the ``nargs`` parameter.  The values are then stored as a tuple.139140.. click:example::141142    @click.command()143    @click.option('--pos', nargs=2, type=float)144    def findme(pos):145        a, b = pos146        click.echo(f"{a} / {b}")147148And on the command line:149150.. click:run::151152    invoke(findme, args=['--pos', '2.0', '3.0'])153154.. _tuple-type:155156Tuples as Multi Value Options157-----------------------------158159.. versionadded:: 4.0160161As you can see that by using `nargs` set to a specific number each item in162the resulting tuple is of the same type.  This might not be what you want.163Commonly you might want to use different types for different indexes in164the tuple.  For this you can directly specify a tuple as type:165166.. click:example::167168    @click.command()169    @click.option('--item', type=(str, int))170    def putitem(item):171        name, id = item172        click.echo(f"name={name} id={id}")173174And on the command line:175176.. click:run::177178    invoke(putitem, args=['--item', 'peter', '1338'])179180By using a tuple literal as type, `nargs` gets automatically set to the181length of the tuple and the :class:`click.Tuple` type is automatically182used.  The above example is thus equivalent to this:183184.. click:example::185186    @click.command()187    @click.option('--item', nargs=2, type=click.Tuple([str, int]))188    def putitem(item):189        name, id = item190        click.echo(f"name={name} id={id}")191192.. _multiple-options:193194Multiple Options195----------------196197Similarly to ``nargs``, there is also the case of wanting to support a198parameter being provided multiple times and have all the values recorded --199not just the last one.  For instance, ``git commit -m foo -m bar`` would200record two lines for the commit message: ``foo`` and ``bar``. This can be201accomplished with the ``multiple`` flag:202203Example:204205.. click:example::206207    @click.command()208    @click.option('--message', '-m', multiple=True)209    def commit(message):210        click.echo('\n'.join(message))211212And on the command line:213214.. click:run::215216    invoke(commit, args=['-m', 'foo', '-m', 'bar'])217218When passing a ``default`` with ``multiple=True``, the default value219must be a list or tuple, otherwise it will be interpreted as a list of220single characters.221222.. code-block:: python223224    @click.option("--format", multiple=True, default=["json"])225226227Counting228--------229230In some very rare circumstances, it is interesting to use the repetition231of options to count an integer up.  This can be used for verbosity flags,232for instance:233234.. click:example::235236    @click.command()237    @click.option('-v', '--verbose', count=True)238    def log(verbose):239        click.echo(f"Verbosity: {verbose}")240241And on the command line:242243.. click:run::244245    invoke(log, args=['-vvv'])246247Boolean Flags248-------------249250Boolean flags are options that can be enabled or disabled.  This can be251accomplished by defining two flags in one go separated by a slash (``/``)252for enabling or disabling the option.  (If a slash is in an option string,253Click automatically knows that it's a boolean flag and will pass254``is_flag=True`` implicitly.)  Click always wants you to provide an enable255and disable flag so that you can change the default later.256257Example:258259.. click:example::260261    import sys262263    @click.command()264    @click.option('--shout/--no-shout', default=False)265    def info(shout):266        rv = sys.platform267        if shout:268            rv = rv.upper() + '!!!!111'269        click.echo(rv)270271And on the command line:272273.. click:run::274275    invoke(info, args=['--shout'])276    invoke(info, args=['--no-shout'])277    invoke(info)278279If you really don't want an off-switch, you can just define one and280manually inform Click that something is a flag:281282.. click:example::283284    import sys285286    @click.command()287    @click.option('--shout', is_flag=True)288    def info(shout):289        rv = sys.platform290        if shout:291            rv = rv.upper() + '!!!!111'292        click.echo(rv)293294And on the command line:295296.. click:run::297298    invoke(info, args=['--shout'])299    invoke(info)300301Note that if a slash is contained in your option already (for instance, if302you use Windows-style parameters where ``/`` is the prefix character), you303can alternatively split the parameters through ``;`` instead:304305.. click:example::306307    @click.command()308    @click.option('/debug;/no-debug')309    def log(debug):310        click.echo(f"debug={debug}")311312    if __name__ == '__main__':313        log()314315.. versionchanged:: 6.0316317If you want to define an alias for the second option only, then you will318need to use leading whitespace to disambiguate the format string:319320Example:321322.. click:example::323324    import sys325326    @click.command()327    @click.option('--shout/--no-shout', ' /-S', default=False)328    def info(shout):329        rv = sys.platform330        if shout:331            rv = rv.upper() + '!!!!111'332        click.echo(rv)333334.. click:run::335336    invoke(info, args=['--help'])337338Feature Switches339----------------340341In addition to boolean flags, there are also feature switches.  These are342implemented by setting multiple options to the same parameter name and343defining a flag value.  Note that by providing the ``flag_value`` parameter,344Click will implicitly set ``is_flag=True``.345346To set a default flag, assign a value of `True` to the flag that should be347the default.348349.. click:example::350351    import sys352353    @click.command()354    @click.option('--upper', 'transformation', flag_value='upper',355                  default=True)356    @click.option('--lower', 'transformation', flag_value='lower')357    def info(transformation):358        click.echo(getattr(sys.platform, transformation)())359360And on the command line:361362.. click:run::363364    invoke(info, args=['--upper'])365    invoke(info, args=['--lower'])366    invoke(info)367368.. _choice-opts:369370Choice Options371--------------372373Sometimes, you want to have a parameter be a choice of a list of values.374In that case you can use :class:`Choice` type.  It can be instantiated375with a list of valid values.  The originally passed choice will be returned,376not the str passed on the command line.  Token normalization functions and377``case_sensitive=False`` can cause the two to be different but still match.378379Example:380381.. click:example::382383    @click.command()384    @click.option('--hash-type',385                  type=click.Choice(['MD5', 'SHA1'], case_sensitive=False))386    def digest(hash_type):387        click.echo(hash_type)388389What it looks like:390391.. click:run::392393    invoke(digest, args=['--hash-type=MD5'])394    println()395    invoke(digest, args=['--hash-type=md5'])396    println()397    invoke(digest, args=['--hash-type=foo'])398    println()399    invoke(digest, args=['--help'])400401Only pass the choices as list or tuple. Other iterables (like402generators) may lead to unexpected results.403404Choices work with options that have ``multiple=True``. If a ``default``405value is given with ``multiple=True``, it should be a list or tuple of406valid choices.407408Choices should be unique after considering the effects of409``case_sensitive`` and any specified token normalization function.410411.. versionchanged:: 7.1412    The resulting value from an option will always be one of the413    originally passed choices regardless of ``case_sensitive``.414415.. _option-prompting:416417Prompting418---------419420In some cases, you want parameters that can be provided from the command line,421but if not provided, ask for user input instead.  This can be implemented with422Click by defining a prompt string.423424Example:425426.. click:example::427428    @click.command()429    @click.option('--name', prompt=True)430    def hello(name):431        click.echo(f"Hello {name}!")432433And what it looks like:434435.. click:run::436437    invoke(hello, args=['--name=John'])438    invoke(hello, input=['John'])439440If you are not happy with the default prompt string, you can ask for441a different one:442443.. click:example::444445    @click.command()446    @click.option('--name', prompt='Your name please')447    def hello(name):448        click.echo(f"Hello {name}!")449450What it looks like:451452.. click:run::453454    invoke(hello, input=['John'])455456It is advised that prompt not be used in conjunction with the multiple457flag set to True. Instead, prompt in the function interactively.458459By default, the user will be prompted for an input if one was not passed460through the command line. To turn this behavior off, see461:ref:`optional-value`.462463464Password Prompts465----------------466467Click also supports hidden prompts and asking for confirmation.  This is468useful for password input:469470.. click:example::471472    import codecs473474    @click.command()475    @click.option(476        "--password", prompt=True, hide_input=True,477        confirmation_prompt=True478    )479    def encode(password):480        click.echo(f"encoded: {codecs.encode(password, 'rot13')}")481482.. click:run::483484    invoke(encode, input=['secret', 'secret'])485486Because this combination of parameters is quite common, this can also be487replaced with the :func:`password_option` decorator:488489.. code-block:: python490491    @click.command()492    @click.password_option()493    def encrypt(password):494        click.echo(f"encoded: to {codecs.encode(password, 'rot13')}")495496497Dynamic Defaults for Prompts498----------------------------499500The ``auto_envvar_prefix`` and ``default_map`` options for the context501allow the program to read option values from the environment or a502configuration file.  However, this overrides the prompting mechanism, so503that the user does not get the option to change the value interactively.504505If you want to let the user configure the default value, but still be506prompted if the option isn't specified on the command line, you can do so507by supplying a callable as the default value. For example, to get a default508from the environment:509510.. code-block:: python511512    import os513514    @click.command()515    @click.option(516        "--username", prompt=True,517        default=lambda: os.environ.get("USER", "")518    )519    def hello(username):520        click.echo(f"Hello, {username}!")521522To describe what the default value will be, set it in ``show_default``.523524.. click:example::525526    import os527528    @click.command()529    @click.option(530        "--username", prompt=True,531        default=lambda: os.environ.get("USER", ""),532        show_default="current user"533    )534    def hello(username):535        click.echo(f"Hello, {username}!")536537.. click:run::538539   invoke(hello, args=["--help"])540541542Callbacks and Eager Options543---------------------------544545Sometimes, you want a parameter to completely change the execution flow.546For instance, this is the case when you want to have a ``--version``547parameter that prints out the version and then exits the application.548549Note: an actual implementation of a ``--version`` parameter that is550reusable is available in Click as :func:`click.version_option`.  The code551here is merely an example of how to implement such a flag.552553In such cases, you need two concepts: eager parameters and a callback.  An554eager parameter is a parameter that is handled before others, and a555callback is what executes after the parameter is handled.  The eagerness556is necessary so that an earlier required parameter does not produce an557error message.  For instance, if ``--version`` was not eager and a558parameter ``--foo`` was required and defined before, you would need to559specify it for ``--version`` to work.  For more information, see560:ref:`callback-evaluation-order`.561562A callback is a function that is invoked with three parameters: the563current :class:`Context`, the current :class:`Parameter`, and the value.564The context provides some useful features such as quitting the565application and gives access to other already processed parameters.566567Here's an example for a ``--version`` flag:568569.. click:example::570571    def print_version(ctx, param, value):572        if not value or ctx.resilient_parsing:573            return574        click.echo('Version 1.0')575        ctx.exit()576577    @click.command()578    @click.option('--version', is_flag=True, callback=print_version,579                  expose_value=False, is_eager=True)580    def hello():581        click.echo('Hello World!')582583The `expose_value` parameter prevents the pretty pointless ``version``584parameter from being passed to the callback.  If that was not specified, a585boolean would be passed to the `hello` script.  The `resilient_parsing`586flag is applied to the context if Click wants to parse the command line587without any destructive behavior that would change the execution flow.  In588this case, because we would exit the program, we instead do nothing.589590What it looks like:591592.. click:run::593594    invoke(hello)595    invoke(hello, args=['--version'])596597598Yes Parameters599--------------600601For dangerous operations, it's very useful to be able to ask a user for602confirmation.  This can be done by adding a boolean ``--yes`` flag and603asking for confirmation if the user did not provide it and to fail in a604callback:605606.. click:example::607608    def abort_if_false(ctx, param, value):609        if not value:610            ctx.abort()611612    @click.command()613    @click.option('--yes', is_flag=True, callback=abort_if_false,614                  expose_value=False,615                  prompt='Are you sure you want to drop the db?')616    def dropdb():617        click.echo('Dropped all tables!')618619And what it looks like on the command line:620621.. click:run::622623    invoke(dropdb, input=['n'])624    invoke(dropdb, args=['--yes'])625626Because this combination of parameters is quite common, this can also be627replaced with the :func:`confirmation_option` decorator:628629.. click:example::630631    @click.command()632    @click.confirmation_option(prompt='Are you sure you want to drop the db?')633    def dropdb():634        click.echo('Dropped all tables!')635636637Values from Environment Variables638---------------------------------639640A very useful feature of Click is the ability to accept parameters from641environment variables in addition to regular parameters.  This allows642tools to be automated much easier.  For instance, you might want to pass643a configuration file with a ``--config`` parameter but also support exporting644a ``TOOL_CONFIG=hello.cfg`` key-value pair for a nicer development645experience.646647This is supported by Click in two ways.  One is to automatically build648environment variables which is supported for options only.  To enable this649feature, the ``auto_envvar_prefix`` parameter needs to be passed to the650script that is invoked.  Each command and parameter is then added as an651uppercase underscore-separated variable.  If you have a subcommand652called ``run`` taking an option called ``reload`` and the prefix is653``WEB``, then the variable is ``WEB_RUN_RELOAD``.654655Example usage:656657.. click:example::658659    @click.command()660    @click.option('--username')661    def greet(username):662        click.echo(f'Hello {username}!')663664    if __name__ == '__main__':665        greet(auto_envvar_prefix='GREETER')666667And from the command line:668669.. click:run::670671    invoke(greet, env={'GREETER_USERNAME': 'john'},672           auto_envvar_prefix='GREETER')673674When using ``auto_envvar_prefix`` with command groups, the command name675needs to be included in the environment variable, between the prefix and676the parameter name, *i.e.* ``PREFIX_COMMAND_VARIABLE``. If you have a677subcommand called ``run-server`` taking an option called ``host`` and678the prefix is ``WEB``, then the variable is ``WEB_RUN_SERVER_HOST``.679680Example:681682.. click:example::683684   @click.group()685   @click.option('--debug/--no-debug')686   def cli(debug):687       click.echo(f"Debug mode is {'on' if debug else 'off'}")688689   @cli.command()690   @click.option('--username')691   def greet(username):692       click.echo(f"Hello {username}!")693694   if __name__ == '__main__':695       cli(auto_envvar_prefix='GREETER')696697.. click:run::698699   invoke(cli, args=['greet',],700          env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},701          auto_envvar_prefix='GREETER')702703704The second option is to manually pull values in from specific environment705variables by defining the name of the environment variable on the option.706707Example usage:708709.. click:example::710711    @click.command()712    @click.option('--username', envvar='USERNAME')713    def greet(username):714       click.echo(f"Hello {username}!")715716    if __name__ == '__main__':717        greet()718719And from the command line:720721.. click:run::722723    invoke(greet, env={'USERNAME': 'john'})724725In that case it can also be a list of different environment variables726where the first one is picked.727728Multiple Values from Environment Values729---------------------------------------730731As options can accept multiple values, pulling in such values from732environment variables (which are strings) is a bit more complex.  The way733Click solves this is by leaving it up to the type to customize this734behavior.  For both ``multiple`` and ``nargs`` with values other than735``1``, Click will invoke the :meth:`ParamType.split_envvar_value` method to736perform the splitting.737738The default implementation for all types is to split on whitespace.  The739exceptions to this rule are the :class:`File` and :class:`Path` types740which both split according to the operating system's path splitting rules.741On Unix systems like Linux and OS X, the splitting happens for those on742every colon (``:``), and for Windows, on every semicolon (``;``).743744Example usage:745746.. click:example::747748    @click.command()749    @click.option('paths', '--path', envvar='PATHS', multiple=True,750                  type=click.Path())751    def perform(paths):752        for path in paths:753            click.echo(path)754755    if __name__ == '__main__':756        perform()757758And from the command line:759760.. click:run::761762    import os763    invoke(perform, env={"PATHS": f"./foo/bar{os.path.pathsep}./test"})764765Other Prefix Characters766-----------------------767768Click can deal with alternative prefix characters other than ``-`` for769options.  This is for instance useful if you want to handle slashes as770parameters ``/`` or something similar.  Note that this is strongly771discouraged in general because Click wants developers to stay close to772POSIX semantics.  However in certain situations this can be useful:773774.. click:example::775776    @click.command()777    @click.option('+w/-w')778    def chmod(w):779        click.echo(f"writable={w}")780781    if __name__ == '__main__':782        chmod()783784And from the command line:785786.. click:run::787788    invoke(chmod, args=['+w'])789    invoke(chmod, args=['-w'])790791Note that if you are using ``/`` as prefix character and you want to use a792boolean flag you need to separate it with ``;`` instead of ``/``:793794.. click:example::795796    @click.command()797    @click.option('/debug;/no-debug')798    def log(debug):799        click.echo(f"debug={debug}")800801    if __name__ == '__main__':802        log()803804.. _ranges:805806Range Options807-------------808809The :class:`IntRange` type extends the :data:`INT` type to ensure the810value is contained in the given range. The :class:`FloatRange` type does811the same for :data:`FLOAT`.812813If ``min`` or ``max`` is omitted, that side is *unbounded*. Any value in814that direction is accepted. By default, both bounds are *closed*, which815means the boundary value is included in the accepted range. ``min_open``816and ``max_open`` can be used to exclude that boundary from the range.817818If ``clamp`` mode is enabled, a value that is outside the range is set819to the boundary instead of failing. For example, the range ``0, 5``820would return ``5`` for the value ``10``, or ``0`` for the value ``-1``.821When using :class:`FloatRange`, ``clamp`` can only be enabled if both822bounds are *closed* (the default).823824.. click:example::825826    @click.command()827    @click.option("--count", type=click.IntRange(0, 20, clamp=True))828    @click.option("--digit", type=click.IntRange(0, 9))829    def repeat(count, digit):830        click.echo(str(digit) * count)831832.. click:run::833834    invoke(repeat, args=['--count=100', '--digit=5'])835    invoke(repeat, args=['--count=6', '--digit=12'])836837838Callbacks for Validation839------------------------840841.. versionchanged:: 2.0842843If you want to apply custom validation logic, you can do this in the844parameter callbacks. These callbacks can both modify values as well as845raise errors if the validation does not work. The callback runs after846type conversion. It is called for all sources, including prompts.847848In Click 1.0, you can only raise the :exc:`UsageError` but starting with849Click 2.0, you can also raise the :exc:`BadParameter` error, which has the850added advantage that it will automatically format the error message to851also contain the parameter name.852853.. click:example::854855    def validate_rolls(ctx, param, value):856        if isinstance(value, tuple):857            return value858859        try:860            rolls, _, dice = value.partition("d")861            return int(dice), int(rolls)862        except ValueError:863            raise click.BadParameter("format must be 'NdM'")864865    @click.command()866    @click.option(867        "--rolls", type=click.UNPROCESSED, callback=validate_rolls,868        default="1d6", prompt=True,869    )870    def roll(rolls):871        sides, times = rolls872        click.echo(f"Rolling a {sides}-sided dice {times} time(s)")873874.. click:run::875876    invoke(roll, args=["--rolls=42"])877    println()878    invoke(roll, args=["--rolls=2d12"])879    println()880    invoke(roll, input=["42", "2d12"])881882883.. _optional-value:884885Optional Value886--------------887888Providing the value to an option can be made optional, in which case889providing only the option's flag without a value will either show a890prompt or use its ``flag_value``.891892Setting ``is_flag=False, flag_value=value`` tells Click that the option893can still be passed a value, but if only the flag is given the894``flag_value`` is used.895896.. click:example::897898    @click.command()899    @click.option("--name", is_flag=False, flag_value="Flag", default="Default")900    def hello(name):901        click.echo(f"Hello, {name}!")902903.. click:run::904905    invoke(hello, args=[])906    invoke(hello, args=["--name", "Value"])907    invoke(hello, args=["--name"])908909If the option has ``prompt`` enabled, then setting910``prompt_required=False`` tells Click to only show the prompt if the911option's flag is given, instead of if the option is not provided at all.912913.. click:example::914915    @click.command()916    @click.option('--name', prompt=True, prompt_required=False, default="Default")917    def hello(name):918        click.echo(f"Hello {name}!")919920.. click:run::921922    invoke(hello)923    invoke(hello, args=["--name", "Value"])924    invoke(hello, args=["--name"], input="Prompt")925926If ``required=True``, then the option will still prompt if it is not927given, but it will also prompt if only the flag is given.