Skip to content
Myr

options.rst

This file

Path

docs/options.rst

852 lines · 23.7 KiB

Last changed by

Merge branch '7.x'David Lordbefore adoptionbce4ea4

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'])256257If you really don't want an off-switch, you can just define one and258manually inform Click that something is a flag:259260.. click:example::261262    import sys263264    @click.command()265    @click.option('--shout', is_flag=True)266    def info(shout):267        rv = sys.platform268        if shout:269            rv = rv.upper() + '!!!!111'270        click.echo(rv)271272And on the command line:273274.. click:run::275276    invoke(info, args=['--shout'])277278Note that if a slash is contained in your option already (for instance, if279you use Windows-style parameters where ``/`` is the prefix character), you280can alternatively split the parameters through ``;`` instead:281282.. click:example::283284    @click.command()285    @click.option('/debug;/no-debug')286    def log(debug):287        click.echo(f"debug={debug}")288289    if __name__ == '__main__':290        log()291292.. versionchanged:: 6.0293294If you want to define an alias for the second option only, then you will295need to use leading whitespace to disambiguate the format string:296297Example:298299.. click:example::300301    import sys302303    @click.command()304    @click.option('--shout/--no-shout', ' /-S', default=False)305    def info(shout):306        rv = sys.platform307        if shout:308            rv = rv.upper() + '!!!!111'309        click.echo(rv)310311.. click:run::312313    invoke(info, args=['--help'])314315Feature Switches316----------------317318In addition to boolean flags, there are also feature switches.  These are319implemented by setting multiple options to the same parameter name and320defining a flag value.  Note that by providing the ``flag_value`` parameter,321Click will implicitly set ``is_flag=True``.322323To set a default flag, assign a value of `True` to the flag that should be324the default.325326.. click:example::327328    import sys329330    @click.command()331    @click.option('--upper', 'transformation', flag_value='upper',332                  default=True)333    @click.option('--lower', 'transformation', flag_value='lower')334    def info(transformation):335        click.echo(getattr(sys.platform, transformation)())336337And on the command line:338339.. click:run::340341    invoke(info, args=['--upper'])342    invoke(info, args=['--lower'])343    invoke(info)344345.. _choice-opts:346347Choice Options348--------------349350Sometimes, you want to have a parameter be a choice of a list of values.351In that case you can use :class:`Choice` type.  It can be instantiated352with a list of valid values.  The originally passed choice will be returned,353not the str passed on the command line.  Token normalization functions and354``case_sensitive=False`` can cause the two to be different but still match.355356Example:357358.. click:example::359360    @click.command()361    @click.option('--hash-type',362                  type=click.Choice(['MD5', 'SHA1'], case_sensitive=False))363    def digest(hash_type):364        click.echo(hash_type)365366What it looks like:367368.. click:run::369370    invoke(digest, args=['--hash-type=MD5'])371    println()372    invoke(digest, args=['--hash-type=md5'])373    println()374    invoke(digest, args=['--hash-type=foo'])375    println()376    invoke(digest, args=['--help'])377378Only pass the choices as list or tuple. Other iterables (like379generators) may lead to unexpected results.380381Choices work with options that have ``multiple=True``. If a ``default``382value is given with ``multiple=True``, it should be a list or tuple of383valid choices.384385Choices should be unique after considering the effects of386``case_sensitive`` and any specified token normalization function.387388.. versionchanged:: 7.1389    The resulting value from an option will always be one of the390    originally passed choices regardless of ``case_sensitive``.391392.. _option-prompting:393394Prompting395---------396397In some cases, you want parameters that can be provided from the command line,398but if not provided, ask for user input instead.  This can be implemented with399Click by defining a prompt string.400401Example:402403.. click:example::404405    @click.command()406    @click.option('--name', prompt=True)407    def hello(name):408        click.echo(f"Hello {name}!")409410And what it looks like:411412.. click:run::413414    invoke(hello, args=['--name=John'])415    invoke(hello, input=['John'])416417If you are not happy with the default prompt string, you can ask for418a different one:419420.. click:example::421422    @click.command()423    @click.option('--name', prompt='Your name please')424    def hello(name):425        click.echo(f"Hello {name}!")426427What it looks like:428429.. click:run::430431    invoke(hello, input=['John'])432433It is advised that prompt not be used in conjunction with the multiple434flag set to True. Instead, prompt in the function interactively.435436437Password Prompts438----------------439440Click also supports hidden prompts and asking for confirmation.  This is441useful for password input:442443.. click:example::444445    @click.command()446    @click.option('--password', prompt=True, hide_input=True,447                  confirmation_prompt=True)448    def encrypt(password):449        click.echo(f"Encrypting password to {password.encode('rot13')}")450451What it looks like:452453.. click:run::454455    invoke(encrypt, input=['secret', 'secret'])456457Because this combination of parameters is quite common, this can also be458replaced with the :func:`password_option` decorator:459460.. click:example::461462    @click.command()463    @click.password_option()464    def encrypt(password):465        click.echo(f"Encrypting password to {password.encode('rot13')}")466467Dynamic Defaults for Prompts468----------------------------469470The ``auto_envvar_prefix`` and ``default_map`` options for the context471allow the program to read option values from the environment or a472configuration file.  However, this overrides the prompting mechanism, so473that the user does not get the option to change the value interactively.474475If you want to let the user configure the default value, but still be476prompted if the option isn't specified on the command line, you can do so477by supplying a callable as the default value. For example, to get a default478from the environment:479480.. click:example::481482    @click.command()483    @click.option('--username', prompt=True,484                  default=lambda: os.environ.get('USER', ''))485    def hello(username):486        print("Hello,", username)487488To describe what the default value will be, set it in ``show_default``.489490.. click:example::491492    @click.command()493    @click.option('--username', prompt=True,494                  default=lambda: os.environ.get('USER', ''),495                  show_default='current user')496    def hello(username):497        print("Hello,", username)498499.. click:run::500501   invoke(hello, args=['--help'])502503Callbacks and Eager Options504---------------------------505506Sometimes, you want a parameter to completely change the execution flow.507For instance, this is the case when you want to have a ``--version``508parameter that prints out the version and then exits the application.509510Note: an actual implementation of a ``--version`` parameter that is511reusable is available in Click as :func:`click.version_option`.  The code512here is merely an example of how to implement such a flag.513514In such cases, you need two concepts: eager parameters and a callback.  An515eager parameter is a parameter that is handled before others, and a516callback is what executes after the parameter is handled.  The eagerness517is necessary so that an earlier required parameter does not produce an518error message.  For instance, if ``--version`` was not eager and a519parameter ``--foo`` was required and defined before, you would need to520specify it for ``--version`` to work.  For more information, see521:ref:`callback-evaluation-order`.522523A callback is a function that is invoked with two parameters: the current524:class:`Context` and the value.  The context provides some useful features525such as quitting the application and gives access to other already526processed parameters.527528Here an example for a ``--version`` flag:529530.. click:example::531532    def print_version(ctx, param, value):533        if not value or ctx.resilient_parsing:534            return535        click.echo('Version 1.0')536        ctx.exit()537538    @click.command()539    @click.option('--version', is_flag=True, callback=print_version,540                  expose_value=False, is_eager=True)541    def hello():542        click.echo('Hello World!')543544The `expose_value` parameter prevents the pretty pointless ``version``545parameter from being passed to the callback.  If that was not specified, a546boolean would be passed to the `hello` script.  The `resilient_parsing`547flag is applied to the context if Click wants to parse the command line548without any destructive behavior that would change the execution flow.  In549this case, because we would exit the program, we instead do nothing.550551What it looks like:552553.. click:run::554555    invoke(hello)556    invoke(hello, args=['--version'])557558.. admonition:: Callback Signature Changes559560    In Click 2.0 the signature for callbacks changed.  For more561    information about these changes see :ref:`upgrade-to-2.0`.562563Yes Parameters564--------------565566For dangerous operations, it's very useful to be able to ask a user for567confirmation.  This can be done by adding a boolean ``--yes`` flag and568asking for confirmation if the user did not provide it and to fail in a569callback:570571.. click:example::572573    def abort_if_false(ctx, param, value):574        if not value:575            ctx.abort()576577    @click.command()578    @click.option('--yes', is_flag=True, callback=abort_if_false,579                  expose_value=False,580                  prompt='Are you sure you want to drop the db?')581    def dropdb():582        click.echo('Dropped all tables!')583584And what it looks like on the command line:585586.. click:run::587588    invoke(dropdb, input=['n'])589    invoke(dropdb, args=['--yes'])590591Because this combination of parameters is quite common, this can also be592replaced with the :func:`confirmation_option` decorator:593594.. click:example::595596    @click.command()597    @click.confirmation_option(prompt='Are you sure you want to drop the db?')598    def dropdb():599        click.echo('Dropped all tables!')600601.. admonition:: Callback Signature Changes602603    In Click 2.0 the signature for callbacks changed.  For more604    information about these changes see :ref:`upgrade-to-2.0`.605606Values from Environment Variables607---------------------------------608609A very useful feature of Click is the ability to accept parameters from610environment variables in addition to regular parameters.  This allows611tools to be automated much easier.  For instance, you might want to pass612a configuration file with a ``--config`` parameter but also support exporting613a ``TOOL_CONFIG=hello.cfg`` key-value pair for a nicer development614experience.615616This is supported by Click in two ways.  One is to automatically build617environment variables which is supported for options only.  To enable this618feature, the ``auto_envvar_prefix`` parameter needs to be passed to the619script that is invoked.  Each command and parameter is then added as an620uppercase underscore-separated variable.  If you have a subcommand621called ``run`` taking an option called ``reload`` and the prefix is622``WEB``, then the variable is ``WEB_RUN_RELOAD``.623624Example usage:625626.. click:example::627628    @click.command()629    @click.option('--username')630    def greet(username):631        click.echo(f'Hello {username}!')632633    if __name__ == '__main__':634        greet(auto_envvar_prefix='GREETER')635636And from the command line:637638.. click:run::639640    invoke(greet, env={'GREETER_USERNAME': 'john'},641           auto_envvar_prefix='GREETER')642643When using ``auto_envvar_prefix`` with command groups, the command name644needs to be included in the environment variable, between the prefix and645the parameter name, *i.e.* ``PREFIX_COMMAND_VARIABLE``. If you have a646subcommand called ``run-server`` taking an option called ``host`` and647the prefix is ``WEB``, then the variable is ``WEB_RUN_SERVER_HOST``.648649Example:650651.. click:example::652653   @click.group()654   @click.option('--debug/--no-debug')655   def cli(debug):656       click.echo(f"Debug mode is {'on' if debug else 'off'}")657658   @cli.command()659   @click.option('--username')660   def greet(username):661       click.echo(f"Hello {username}!")662663   if __name__ == '__main__':664       cli(auto_envvar_prefix='GREETER')665666.. click:run::667668   invoke(cli, args=['greet',],669          env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},670          auto_envvar_prefix='GREETER')671672673The second option is to manually pull values in from specific environment674variables by defining the name of the environment variable on the option.675676Example usage:677678.. click:example::679680    @click.command()681    @click.option('--username', envvar='USERNAME')682    def greet(username):683       click.echo(f"Hello {username}!")684685    if __name__ == '__main__':686        greet()687688And from the command line:689690.. click:run::691692    invoke(greet, env={'USERNAME': 'john'})693694In that case it can also be a list of different environment variables695where the first one is picked.696697Multiple Values from Environment Values698---------------------------------------699700As options can accept multiple values, pulling in such values from701environment variables (which are strings) is a bit more complex.  The way702Click solves this is by leaving it up to the type to customize this703behavior.  For both ``multiple`` and ``nargs`` with values other than704``1``, Click will invoke the :meth:`ParamType.split_envvar_value` method to705perform the splitting.706707The default implementation for all types is to split on whitespace.  The708exceptions to this rule are the :class:`File` and :class:`Path` types709which both split according to the operating system's path splitting rules.710On Unix systems like Linux and OS X, the splitting happens for those on711every colon (``:``), and for Windows, on every semicolon (``;``).712713Example usage:714715.. click:example::716717    @click.command()718    @click.option('paths', '--path', envvar='PATHS', multiple=True,719                  type=click.Path())720    def perform(paths):721        for path in paths:722            click.echo(path)723724    if __name__ == '__main__':725        perform()726727And from the command line:728729.. click:run::730731    import os732    invoke(perform, env={"PATHS": f"./foo/bar{os.path.pathsep}./test"})733734Other Prefix Characters735-----------------------736737Click can deal with alternative prefix characters other than ``-`` for738options.  This is for instance useful if you want to handle slashes as739parameters ``/`` or something similar.  Note that this is strongly740discouraged in general because Click wants developers to stay close to741POSIX semantics.  However in certain situations this can be useful:742743.. click:example::744745    @click.command()746    @click.option('+w/-w')747    def chmod(w):748        click.echo(f"writable={w}")749750    if __name__ == '__main__':751        chmod()752753And from the command line:754755.. click:run::756757    invoke(chmod, args=['+w'])758    invoke(chmod, args=['-w'])759760Note that if you are using ``/`` as prefix character and you want to use a761boolean flag you need to separate it with ``;`` instead of ``/``:762763.. click:example::764765    @click.command()766    @click.option('/debug;/no-debug')767    def log(debug):768        click.echo(f"debug={debug}")769770    if __name__ == '__main__':771        log()772773.. _ranges:774775Range Options776-------------777778A special mention should go to the :class:`IntRange` type, which works very779similarly to the :data:`INT` type, but restricts the value to fall into a780specific range (inclusive on both edges).  It has two modes:781782-   the default mode (non-clamping mode) where a value that falls outside783    of the range will cause an error.784-   an optional clamping mode where a value that falls outside of the785    range will be clamped.  This means that a range of ``0-5`` would786    return ``5`` for the value ``10`` or ``0`` for the value ``-1`` (for787    example).788789Example:790791.. click:example::792793    @click.command()794    @click.option('--count', type=click.IntRange(0, 20, clamp=True))795    @click.option('--digit', type=click.IntRange(0, 10))796    def repeat(count, digit):797        click.echo(str(digit) * count)798799    if __name__ == '__main__':800        repeat()801802And from the command line:803804.. click:run::805806    invoke(repeat, args=['--count=1000', '--digit=5'])807    invoke(repeat, args=['--count=1000', '--digit=12'])808809If you pass ``None`` for any of the edges, it means that the range is open810at that side.811812Callbacks for Validation813------------------------814815.. versionchanged:: 2.0816817If you want to apply custom validation logic, you can do this in the818parameter callbacks.  These callbacks can both modify values as well as819raise errors if the validation does not work.820821In Click 1.0, you can only raise the :exc:`UsageError` but starting with822Click 2.0, you can also raise the :exc:`BadParameter` error, which has the823added advantage that it will automatically format the error message to824also contain the parameter name.825826Example:827828.. click:example::829830    def validate_rolls(ctx, param, value):831        try:832            rolls, dice = map(int, value.split('d', 2))833            return (dice, rolls)834        except ValueError:835            raise click.BadParameter('rolls need to be in format NdM')836837    @click.command()838    @click.option('--rolls', callback=validate_rolls, default='1d6')839    def roll(rolls):840        sides, times = rolls841        click.echo(f"Rolling a {sides}-sided dice {times} time(s)")842843    if __name__ == '__main__':844        roll()845846And what it looks like:847848.. click:run::849850    invoke(roll, args=['--rolls=42'])851    println()852    invoke(roll, args=['--rolls=2d12'])