Skip to content
Myr

options.rst

This file

Path

docs/options.rst

900 lines · 25.3 KiB

Last changed by

Added examples of default to boolean flags section (#1697)lrjballbefore adoption297150c

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'])111112Multi Value Options113-------------------114115Sometimes, you have options that take more than one argument.  For options,116only a fixed number of arguments is supported.  This can be configured by117the ``nargs`` parameter.  The values are then stored as a tuple.118119.. click:example::120121    @click.command()122    @click.option('--pos', nargs=2, type=float)123    def findme(pos):124        a, b = pos125        click.echo(f"{a} / {b}")126127And on the command line:128129.. click:run::130131    invoke(findme, args=['--pos', '2.0', '3.0'])132133.. _tuple-type:134135Tuples as Multi Value Options136-----------------------------137138.. versionadded:: 4.0139140As you can see that by using `nargs` set to a specific number each item in141the resulting tuple is of the same type.  This might not be what you want.142Commonly you might want to use different types for different indexes in143the tuple.  For this you can directly specify a tuple as type:144145.. click:example::146147    @click.command()148    @click.option('--item', type=(str, int))149    def putitem(item):150        name, id = item151        click.echo(f"name={name} id={id}")152153And on the command line:154155.. click:run::156157    invoke(putitem, args=['--item', 'peter', '1338'])158159By using a tuple literal as type, `nargs` gets automatically set to the160length of the tuple and the :class:`click.Tuple` type is automatically161used.  The above example is thus equivalent to this:162163.. click:example::164165    @click.command()166    @click.option('--item', nargs=2, type=click.Tuple([str, int]))167    def putitem(item):168        name, id = item169        click.echo(f"name={name} id={id}")170171.. _multiple-options:172173Multiple Options174----------------175176Similarly to ``nargs``, there is also the case of wanting to support a177parameter being provided multiple times and have all the values recorded --178not just the last one.  For instance, ``git commit -m foo -m bar`` would179record two lines for the commit message: ``foo`` and ``bar``. This can be180accomplished with the ``multiple`` flag:181182Example:183184.. click:example::185186    @click.command()187    @click.option('--message', '-m', multiple=True)188    def commit(message):189        click.echo('\n'.join(message))190191And on the command line:192193.. click:run::194195    invoke(commit, args=['-m', 'foo', '-m', 'bar'])196197When passing a ``default`` with ``multiple=True``, the default value198must be a list or tuple, otherwise it will be interpreted as a list of199single characters.200201.. code-block:: python202203    @click.option("--format", multiple=True, default=["json"])204205206Counting207--------208209In some very rare circumstances, it is interesting to use the repetition210of options to count an integer up.  This can be used for verbosity flags,211for instance:212213.. click:example::214215    @click.command()216    @click.option('-v', '--verbose', count=True)217    def log(verbose):218        click.echo(f"Verbosity: {verbose}")219220And on the command line:221222.. click:run::223224    invoke(log, args=['-vvv'])225226Boolean Flags227-------------228229Boolean flags are options that can be enabled or disabled.  This can be230accomplished by defining two flags in one go separated by a slash (``/``)231for enabling or disabling the option.  (If a slash is in an option string,232Click automatically knows that it's a boolean flag and will pass233``is_flag=True`` implicitly.)  Click always wants you to provide an enable234and disable flag so that you can change the default later.235236Example:237238.. click:example::239240    import sys241242    @click.command()243    @click.option('--shout/--no-shout', default=False)244    def info(shout):245        rv = sys.platform246        if shout:247            rv = rv.upper() + '!!!!111'248        click.echo(rv)249250And on the command line:251252.. click:run::253254    invoke(info, args=['--shout'])255    invoke(info, args=['--no-shout'])256    invoke(info)257258If you really don't want an off-switch, you can just define one and259manually inform Click that something is a flag:260261.. click:example::262263    import sys264265    @click.command()266    @click.option('--shout', is_flag=True)267    def info(shout):268        rv = sys.platform269        if shout:270            rv = rv.upper() + '!!!!111'271        click.echo(rv)272273And on the command line:274275.. click:run::276277    invoke(info, args=['--shout'])278    invoke(info)279280Note that if a slash is contained in your option already (for instance, if281you use Windows-style parameters where ``/`` is the prefix character), you282can alternatively split the parameters through ``;`` instead:283284.. click:example::285286    @click.command()287    @click.option('/debug;/no-debug')288    def log(debug):289        click.echo(f"debug={debug}")290291    if __name__ == '__main__':292        log()293294.. versionchanged:: 6.0295296If you want to define an alias for the second option only, then you will297need to use leading whitespace to disambiguate the format string:298299Example:300301.. click:example::302303    import sys304305    @click.command()306    @click.option('--shout/--no-shout', ' /-S', default=False)307    def info(shout):308        rv = sys.platform309        if shout:310            rv = rv.upper() + '!!!!111'311        click.echo(rv)312313.. click:run::314315    invoke(info, args=['--help'])316317Feature Switches318----------------319320In addition to boolean flags, there are also feature switches.  These are321implemented by setting multiple options to the same parameter name and322defining a flag value.  Note that by providing the ``flag_value`` parameter,323Click will implicitly set ``is_flag=True``.324325To set a default flag, assign a value of `True` to the flag that should be326the default.327328.. click:example::329330    import sys331332    @click.command()333    @click.option('--upper', 'transformation', flag_value='upper',334                  default=True)335    @click.option('--lower', 'transformation', flag_value='lower')336    def info(transformation):337        click.echo(getattr(sys.platform, transformation)())338339And on the command line:340341.. click:run::342343    invoke(info, args=['--upper'])344    invoke(info, args=['--lower'])345    invoke(info)346347.. _choice-opts:348349Choice Options350--------------351352Sometimes, you want to have a parameter be a choice of a list of values.353In that case you can use :class:`Choice` type.  It can be instantiated354with a list of valid values.  The originally passed choice will be returned,355not the str passed on the command line.  Token normalization functions and356``case_sensitive=False`` can cause the two to be different but still match.357358Example:359360.. click:example::361362    @click.command()363    @click.option('--hash-type',364                  type=click.Choice(['MD5', 'SHA1'], case_sensitive=False))365    def digest(hash_type):366        click.echo(hash_type)367368What it looks like:369370.. click:run::371372    invoke(digest, args=['--hash-type=MD5'])373    println()374    invoke(digest, args=['--hash-type=md5'])375    println()376    invoke(digest, args=['--hash-type=foo'])377    println()378    invoke(digest, args=['--help'])379380Only pass the choices as list or tuple. Other iterables (like381generators) may lead to unexpected results.382383Choices work with options that have ``multiple=True``. If a ``default``384value is given with ``multiple=True``, it should be a list or tuple of385valid choices.386387Choices should be unique after considering the effects of388``case_sensitive`` and any specified token normalization function.389390.. versionchanged:: 7.1391    The resulting value from an option will always be one of the392    originally passed choices regardless of ``case_sensitive``.393394.. _option-prompting:395396Prompting397---------398399In some cases, you want parameters that can be provided from the command line,400but if not provided, ask for user input instead.  This can be implemented with401Click by defining a prompt string.402403Example:404405.. click:example::406407    @click.command()408    @click.option('--name', prompt=True)409    def hello(name):410        click.echo(f"Hello {name}!")411412And what it looks like:413414.. click:run::415416    invoke(hello, args=['--name=John'])417    invoke(hello, input=['John'])418419If you are not happy with the default prompt string, you can ask for420a different one:421422.. click:example::423424    @click.command()425    @click.option('--name', prompt='Your name please')426    def hello(name):427        click.echo(f"Hello {name}!")428429What it looks like:430431.. click:run::432433    invoke(hello, input=['John'])434435It is advised that prompt not be used in conjunction with the multiple436flag set to True. Instead, prompt in the function interactively.437438By default, the user will be prompted for an input if one was not passed439through the command line. To turn this behavior off, see440:ref:`optional-value`.441442443Password Prompts444----------------445446Click also supports hidden prompts and asking for confirmation.  This is447useful for password input:448449.. click:example::450451    @click.command()452    @click.option('--password', prompt=True, hide_input=True,453                  confirmation_prompt=True)454    def encrypt(password):455        click.echo(f"Encrypting password to {password.encode('rot13')}")456457What it looks like:458459.. click:run::460461    invoke(encrypt, input=['secret', 'secret'])462463Because this combination of parameters is quite common, this can also be464replaced with the :func:`password_option` decorator:465466.. click:example::467468    @click.command()469    @click.password_option()470    def encrypt(password):471        click.echo(f"Encrypting password to {password.encode('rot13')}")472473Dynamic Defaults for Prompts474----------------------------475476The ``auto_envvar_prefix`` and ``default_map`` options for the context477allow the program to read option values from the environment or a478configuration file.  However, this overrides the prompting mechanism, so479that the user does not get the option to change the value interactively.480481If you want to let the user configure the default value, but still be482prompted if the option isn't specified on the command line, you can do so483by supplying a callable as the default value. For example, to get a default484from the environment:485486.. click:example::487488    @click.command()489    @click.option('--username', prompt=True,490                  default=lambda: os.environ.get('USER', ''))491    def hello(username):492        print("Hello,", username)493494To describe what the default value will be, set it in ``show_default``.495496.. click:example::497498    @click.command()499    @click.option('--username', prompt=True,500                  default=lambda: os.environ.get('USER', ''),501                  show_default='current user')502    def hello(username):503        print("Hello,", username)504505.. click:run::506507   invoke(hello, args=['--help'])508509Callbacks and Eager Options510---------------------------511512Sometimes, you want a parameter to completely change the execution flow.513For instance, this is the case when you want to have a ``--version``514parameter that prints out the version and then exits the application.515516Note: an actual implementation of a ``--version`` parameter that is517reusable is available in Click as :func:`click.version_option`.  The code518here is merely an example of how to implement such a flag.519520In such cases, you need two concepts: eager parameters and a callback.  An521eager parameter is a parameter that is handled before others, and a522callback is what executes after the parameter is handled.  The eagerness523is necessary so that an earlier required parameter does not produce an524error message.  For instance, if ``--version`` was not eager and a525parameter ``--foo`` was required and defined before, you would need to526specify it for ``--version`` to work.  For more information, see527:ref:`callback-evaluation-order`.528529A callback is a function that is invoked with two parameters: the current530:class:`Context` and the value.  The context provides some useful features531such as quitting the application and gives access to other already532processed parameters.533534Here an example for a ``--version`` flag:535536.. click:example::537538    def print_version(ctx, param, value):539        if not value or ctx.resilient_parsing:540            return541        click.echo('Version 1.0')542        ctx.exit()543544    @click.command()545    @click.option('--version', is_flag=True, callback=print_version,546                  expose_value=False, is_eager=True)547    def hello():548        click.echo('Hello World!')549550The `expose_value` parameter prevents the pretty pointless ``version``551parameter from being passed to the callback.  If that was not specified, a552boolean would be passed to the `hello` script.  The `resilient_parsing`553flag is applied to the context if Click wants to parse the command line554without any destructive behavior that would change the execution flow.  In555this case, because we would exit the program, we instead do nothing.556557What it looks like:558559.. click:run::560561    invoke(hello)562    invoke(hello, args=['--version'])563564.. admonition:: Callback Signature Changes565566    In Click 2.0 the signature for callbacks changed.  For more567    information about these changes see :ref:`upgrade-to-2.0`.568569Yes Parameters570--------------571572For dangerous operations, it's very useful to be able to ask a user for573confirmation.  This can be done by adding a boolean ``--yes`` flag and574asking for confirmation if the user did not provide it and to fail in a575callback:576577.. click:example::578579    def abort_if_false(ctx, param, value):580        if not value:581            ctx.abort()582583    @click.command()584    @click.option('--yes', is_flag=True, callback=abort_if_false,585                  expose_value=False,586                  prompt='Are you sure you want to drop the db?')587    def dropdb():588        click.echo('Dropped all tables!')589590And what it looks like on the command line:591592.. click:run::593594    invoke(dropdb, input=['n'])595    invoke(dropdb, args=['--yes'])596597Because this combination of parameters is quite common, this can also be598replaced with the :func:`confirmation_option` decorator:599600.. click:example::601602    @click.command()603    @click.confirmation_option(prompt='Are you sure you want to drop the db?')604    def dropdb():605        click.echo('Dropped all tables!')606607.. admonition:: Callback Signature Changes608609    In Click 2.0 the signature for callbacks changed.  For more610    information about these changes see :ref:`upgrade-to-2.0`.611612Values from Environment Variables613---------------------------------614615A very useful feature of Click is the ability to accept parameters from616environment variables in addition to regular parameters.  This allows617tools to be automated much easier.  For instance, you might want to pass618a configuration file with a ``--config`` parameter but also support exporting619a ``TOOL_CONFIG=hello.cfg`` key-value pair for a nicer development620experience.621622This is supported by Click in two ways.  One is to automatically build623environment variables which is supported for options only.  To enable this624feature, the ``auto_envvar_prefix`` parameter needs to be passed to the625script that is invoked.  Each command and parameter is then added as an626uppercase underscore-separated variable.  If you have a subcommand627called ``run`` taking an option called ``reload`` and the prefix is628``WEB``, then the variable is ``WEB_RUN_RELOAD``.629630Example usage:631632.. click:example::633634    @click.command()635    @click.option('--username')636    def greet(username):637        click.echo(f'Hello {username}!')638639    if __name__ == '__main__':640        greet(auto_envvar_prefix='GREETER')641642And from the command line:643644.. click:run::645646    invoke(greet, env={'GREETER_USERNAME': 'john'},647           auto_envvar_prefix='GREETER')648649When using ``auto_envvar_prefix`` with command groups, the command name650needs to be included in the environment variable, between the prefix and651the parameter name, *i.e.* ``PREFIX_COMMAND_VARIABLE``. If you have a652subcommand called ``run-server`` taking an option called ``host`` and653the prefix is ``WEB``, then the variable is ``WEB_RUN_SERVER_HOST``.654655Example:656657.. click:example::658659   @click.group()660   @click.option('--debug/--no-debug')661   def cli(debug):662       click.echo(f"Debug mode is {'on' if debug else 'off'}")663664   @cli.command()665   @click.option('--username')666   def greet(username):667       click.echo(f"Hello {username}!")668669   if __name__ == '__main__':670       cli(auto_envvar_prefix='GREETER')671672.. click:run::673674   invoke(cli, args=['greet',],675          env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},676          auto_envvar_prefix='GREETER')677678679The second option is to manually pull values in from specific environment680variables by defining the name of the environment variable on the option.681682Example usage:683684.. click:example::685686    @click.command()687    @click.option('--username', envvar='USERNAME')688    def greet(username):689       click.echo(f"Hello {username}!")690691    if __name__ == '__main__':692        greet()693694And from the command line:695696.. click:run::697698    invoke(greet, env={'USERNAME': 'john'})699700In that case it can also be a list of different environment variables701where the first one is picked.702703Multiple Values from Environment Values704---------------------------------------705706As options can accept multiple values, pulling in such values from707environment variables (which are strings) is a bit more complex.  The way708Click solves this is by leaving it up to the type to customize this709behavior.  For both ``multiple`` and ``nargs`` with values other than710``1``, Click will invoke the :meth:`ParamType.split_envvar_value` method to711perform the splitting.712713The default implementation for all types is to split on whitespace.  The714exceptions to this rule are the :class:`File` and :class:`Path` types715which both split according to the operating system's path splitting rules.716On Unix systems like Linux and OS X, the splitting happens for those on717every colon (``:``), and for Windows, on every semicolon (``;``).718719Example usage:720721.. click:example::722723    @click.command()724    @click.option('paths', '--path', envvar='PATHS', multiple=True,725                  type=click.Path())726    def perform(paths):727        for path in paths:728            click.echo(path)729730    if __name__ == '__main__':731        perform()732733And from the command line:734735.. click:run::736737    import os738    invoke(perform, env={"PATHS": f"./foo/bar{os.path.pathsep}./test"})739740Other Prefix Characters741-----------------------742743Click can deal with alternative prefix characters other than ``-`` for744options.  This is for instance useful if you want to handle slashes as745parameters ``/`` or something similar.  Note that this is strongly746discouraged in general because Click wants developers to stay close to747POSIX semantics.  However in certain situations this can be useful:748749.. click:example::750751    @click.command()752    @click.option('+w/-w')753    def chmod(w):754        click.echo(f"writable={w}")755756    if __name__ == '__main__':757        chmod()758759And from the command line:760761.. click:run::762763    invoke(chmod, args=['+w'])764    invoke(chmod, args=['-w'])765766Note that if you are using ``/`` as prefix character and you want to use a767boolean flag you need to separate it with ``;`` instead of ``/``:768769.. click:example::770771    @click.command()772    @click.option('/debug;/no-debug')773    def log(debug):774        click.echo(f"debug={debug}")775776    if __name__ == '__main__':777        log()778779.. _ranges:780781Range Options782-------------783784The :class:`IntRange` type extends the :data:`INT` type to ensure the785value is contained in the given range. The :class:`FloatRange` type does786the same for :data:`FLOAT`.787788If ``min`` or ``max`` is omitted, that side is *unbounded*. Any value in789that direction is accepted. By default, both bounds are *closed*, which790means the boundary value is included in the accepted range. ``min_open``791and ``max_open`` can be used to exclude that boundary from the range.792793If ``clamp`` mode is enabled, a value that is outside the range is set794to the boundary instead of failing. For example, the range ``0, 5``795would return ``5`` for the value ``10``, or ``0`` for the value ``-1``.796When using :class:`FloatRange`, ``clamp`` can only be enabled if both797bounds are *closed* (the default).798799.. click:example::800801    @click.command()802    @click.option("--count", type=click.IntRange(0, 20, clamp=True))803    @click.option("--digit", type=click.IntRange(0, 9))804    def repeat(count, digit):805        click.echo(str(digit) * count)806807.. click:run::808809    invoke(repeat, args=['--count=100', '--digit=5'])810    invoke(repeat, args=['--count=6', '--digit=12'])811812813Callbacks for Validation814------------------------815816.. versionchanged:: 2.0817818If you want to apply custom validation logic, you can do this in the819parameter callbacks.  These callbacks can both modify values as well as820raise errors if the validation does not work.821822In Click 1.0, you can only raise the :exc:`UsageError` but starting with823Click 2.0, you can also raise the :exc:`BadParameter` error, which has the824added advantage that it will automatically format the error message to825also contain the parameter name.826827Example:828829.. click:example::830831    def validate_rolls(ctx, param, value):832        try:833            rolls, dice = map(int, value.split('d', 2))834            return (dice, rolls)835        except ValueError:836            raise click.BadParameter('rolls need to be in format NdM')837838    @click.command()839    @click.option('--rolls', callback=validate_rolls, default='1d6')840    def roll(rolls):841        sides, times = rolls842        click.echo(f"Rolling a {sides}-sided dice {times} time(s)")843844    if __name__ == '__main__':845        roll()846847And what it looks like:848849.. click:run::850851    invoke(roll, args=['--rolls=42'])852    println()853    invoke(roll, args=['--rolls=2d12'])854855856.. _optional-value:857858Optional Value859--------------860861Providing the value to an option can be made optional, in which case862providing only the option's flag without a value will either show a863prompt or use its ``flag_value``.864865Setting ``is_flag=False, flag_value=value`` tells Click that the option866can still be passed a value, but if only the flag is given the867``flag_value`` is used.868869.. click:example::870871    @click.command()872    @click.option("--name", is_flag=False, flag_value="Flag", default="Default")873    def hello(name):874        click.echo(f"Hello, {name}!")875876.. click:run::877878    invoke(hello, args=[])879    invoke(hello, args=["--name", "Value"])880    invoke(hello, args=["--name"])881882If the option has ``prompt`` enabled, then setting883``prompt_required=False`` tells Click to only show the prompt if the884option's flag is given, instead of if the option is not provided at all.885886.. click:example::887888    @click.command()889    @click.option('--name', prompt=True, prompt_required=False, default="Default")890    def hello(name):891        click.echo(f"Hello {name}!")892893.. click:run::894895    invoke(hello)896    invoke(hello, args=["--name", "Value"])897    invoke(hello, args=["--name"], input="Prompt")898899If ``required=True``, then the option will still prompt if it is not900given, but it will also prompt if only the flag is given.