Skip to content
Myr

options.rst

This file

Path

docs/options.rst

914 lines · 25.5 KiB

Last changed by

Merge pull request #1785 from MLH-Fellowship/sanitize-inputDavid Lordbefore adoption80086c4

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    import codecs452453    @click.command()454    @click.option(455        "--password", prompt=True, hide_input=True,456        confirmation_prompt=True457    )458    def encode(password):459        click.echo(f"encoded: {codecs.encode(password, 'rot13')}")460461.. click:run::462463    invoke(encode, input=['secret', 'secret'])464465Because this combination of parameters is quite common, this can also be466replaced with the :func:`password_option` decorator:467468.. code-block:: python469470    @click.command()471    @click.password_option()472    def encrypt(password):473        click.echo(f"encoded: to {codecs.encode(password, 'rot13')}")474475476Dynamic Defaults for Prompts477----------------------------478479The ``auto_envvar_prefix`` and ``default_map`` options for the context480allow the program to read option values from the environment or a481configuration file.  However, this overrides the prompting mechanism, so482that the user does not get the option to change the value interactively.483484If you want to let the user configure the default value, but still be485prompted if the option isn't specified on the command line, you can do so486by supplying a callable as the default value. For example, to get a default487from the environment:488489.. code-block:: python490491    import os492493    @click.command()494    @click.option(495        "--username", prompt=True,496        default=lambda: os.environ.get("USER", "")497    )498    def hello(username):499        click.echo(f"Hello, {username}!")500501To describe what the default value will be, set it in ``show_default``.502503.. click:example::504505    import os506507    @click.command()508    @click.option(509        "--username", prompt=True,510        default=lambda: os.environ.get("USER", ""),511        show_default="current user"512    )513    def hello(username):514        click.echo(f"Hello, {username}!")515516.. click:run::517518   invoke(hello, args=["--help"])519520521Callbacks and Eager Options522---------------------------523524Sometimes, you want a parameter to completely change the execution flow.525For instance, this is the case when you want to have a ``--version``526parameter that prints out the version and then exits the application.527528Note: an actual implementation of a ``--version`` parameter that is529reusable is available in Click as :func:`click.version_option`.  The code530here is merely an example of how to implement such a flag.531532In such cases, you need two concepts: eager parameters and a callback.  An533eager parameter is a parameter that is handled before others, and a534callback is what executes after the parameter is handled.  The eagerness535is necessary so that an earlier required parameter does not produce an536error message.  For instance, if ``--version`` was not eager and a537parameter ``--foo`` was required and defined before, you would need to538specify it for ``--version`` to work.  For more information, see539:ref:`callback-evaluation-order`.540541A callback is a function that is invoked with two parameters: the current542:class:`Context` and the value.  The context provides some useful features543such as quitting the application and gives access to other already544processed parameters.545546Here an example for a ``--version`` flag:547548.. click:example::549550    def print_version(ctx, param, value):551        if not value or ctx.resilient_parsing:552            return553        click.echo('Version 1.0')554        ctx.exit()555556    @click.command()557    @click.option('--version', is_flag=True, callback=print_version,558                  expose_value=False, is_eager=True)559    def hello():560        click.echo('Hello World!')561562The `expose_value` parameter prevents the pretty pointless ``version``563parameter from being passed to the callback.  If that was not specified, a564boolean would be passed to the `hello` script.  The `resilient_parsing`565flag is applied to the context if Click wants to parse the command line566without any destructive behavior that would change the execution flow.  In567this case, because we would exit the program, we instead do nothing.568569What it looks like:570571.. click:run::572573    invoke(hello)574    invoke(hello, args=['--version'])575576.. admonition:: Callback Signature Changes577578    In Click 2.0 the signature for callbacks changed.  For more579    information about these changes see :ref:`upgrade-to-2.0`.580581Yes Parameters582--------------583584For dangerous operations, it's very useful to be able to ask a user for585confirmation.  This can be done by adding a boolean ``--yes`` flag and586asking for confirmation if the user did not provide it and to fail in a587callback:588589.. click:example::590591    def abort_if_false(ctx, param, value):592        if not value:593            ctx.abort()594595    @click.command()596    @click.option('--yes', is_flag=True, callback=abort_if_false,597                  expose_value=False,598                  prompt='Are you sure you want to drop the db?')599    def dropdb():600        click.echo('Dropped all tables!')601602And what it looks like on the command line:603604.. click:run::605606    invoke(dropdb, input=['n'])607    invoke(dropdb, args=['--yes'])608609Because this combination of parameters is quite common, this can also be610replaced with the :func:`confirmation_option` decorator:611612.. click:example::613614    @click.command()615    @click.confirmation_option(prompt='Are you sure you want to drop the db?')616    def dropdb():617        click.echo('Dropped all tables!')618619.. admonition:: Callback Signature Changes620621    In Click 2.0 the signature for callbacks changed.  For more622    information about these changes see :ref:`upgrade-to-2.0`.623624Values from Environment Variables625---------------------------------626627A very useful feature of Click is the ability to accept parameters from628environment variables in addition to regular parameters.  This allows629tools to be automated much easier.  For instance, you might want to pass630a configuration file with a ``--config`` parameter but also support exporting631a ``TOOL_CONFIG=hello.cfg`` key-value pair for a nicer development632experience.633634This is supported by Click in two ways.  One is to automatically build635environment variables which is supported for options only.  To enable this636feature, the ``auto_envvar_prefix`` parameter needs to be passed to the637script that is invoked.  Each command and parameter is then added as an638uppercase underscore-separated variable.  If you have a subcommand639called ``run`` taking an option called ``reload`` and the prefix is640``WEB``, then the variable is ``WEB_RUN_RELOAD``.641642Example usage:643644.. click:example::645646    @click.command()647    @click.option('--username')648    def greet(username):649        click.echo(f'Hello {username}!')650651    if __name__ == '__main__':652        greet(auto_envvar_prefix='GREETER')653654And from the command line:655656.. click:run::657658    invoke(greet, env={'GREETER_USERNAME': 'john'},659           auto_envvar_prefix='GREETER')660661When using ``auto_envvar_prefix`` with command groups, the command name662needs to be included in the environment variable, between the prefix and663the parameter name, *i.e.* ``PREFIX_COMMAND_VARIABLE``. If you have a664subcommand called ``run-server`` taking an option called ``host`` and665the prefix is ``WEB``, then the variable is ``WEB_RUN_SERVER_HOST``.666667Example:668669.. click:example::670671   @click.group()672   @click.option('--debug/--no-debug')673   def cli(debug):674       click.echo(f"Debug mode is {'on' if debug else 'off'}")675676   @cli.command()677   @click.option('--username')678   def greet(username):679       click.echo(f"Hello {username}!")680681   if __name__ == '__main__':682       cli(auto_envvar_prefix='GREETER')683684.. click:run::685686   invoke(cli, args=['greet',],687          env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},688          auto_envvar_prefix='GREETER')689690691The second option is to manually pull values in from specific environment692variables by defining the name of the environment variable on the option.693694Example usage:695696.. click:example::697698    @click.command()699    @click.option('--username', envvar='USERNAME')700    def greet(username):701       click.echo(f"Hello {username}!")702703    if __name__ == '__main__':704        greet()705706And from the command line:707708.. click:run::709710    invoke(greet, env={'USERNAME': 'john'})711712In that case it can also be a list of different environment variables713where the first one is picked.714715Multiple Values from Environment Values716---------------------------------------717718As options can accept multiple values, pulling in such values from719environment variables (which are strings) is a bit more complex.  The way720Click solves this is by leaving it up to the type to customize this721behavior.  For both ``multiple`` and ``nargs`` with values other than722``1``, Click will invoke the :meth:`ParamType.split_envvar_value` method to723perform the splitting.724725The default implementation for all types is to split on whitespace.  The726exceptions to this rule are the :class:`File` and :class:`Path` types727which both split according to the operating system's path splitting rules.728On Unix systems like Linux and OS X, the splitting happens for those on729every colon (``:``), and for Windows, on every semicolon (``;``).730731Example usage:732733.. click:example::734735    @click.command()736    @click.option('paths', '--path', envvar='PATHS', multiple=True,737                  type=click.Path())738    def perform(paths):739        for path in paths:740            click.echo(path)741742    if __name__ == '__main__':743        perform()744745And from the command line:746747.. click:run::748749    import os750    invoke(perform, env={"PATHS": f"./foo/bar{os.path.pathsep}./test"})751752Other Prefix Characters753-----------------------754755Click can deal with alternative prefix characters other than ``-`` for756options.  This is for instance useful if you want to handle slashes as757parameters ``/`` or something similar.  Note that this is strongly758discouraged in general because Click wants developers to stay close to759POSIX semantics.  However in certain situations this can be useful:760761.. click:example::762763    @click.command()764    @click.option('+w/-w')765    def chmod(w):766        click.echo(f"writable={w}")767768    if __name__ == '__main__':769        chmod()770771And from the command line:772773.. click:run::774775    invoke(chmod, args=['+w'])776    invoke(chmod, args=['-w'])777778Note that if you are using ``/`` as prefix character and you want to use a779boolean flag you need to separate it with ``;`` instead of ``/``:780781.. click:example::782783    @click.command()784    @click.option('/debug;/no-debug')785    def log(debug):786        click.echo(f"debug={debug}")787788    if __name__ == '__main__':789        log()790791.. _ranges:792793Range Options794-------------795796The :class:`IntRange` type extends the :data:`INT` type to ensure the797value is contained in the given range. The :class:`FloatRange` type does798the same for :data:`FLOAT`.799800If ``min`` or ``max`` is omitted, that side is *unbounded*. Any value in801that direction is accepted. By default, both bounds are *closed*, which802means the boundary value is included in the accepted range. ``min_open``803and ``max_open`` can be used to exclude that boundary from the range.804805If ``clamp`` mode is enabled, a value that is outside the range is set806to the boundary instead of failing. For example, the range ``0, 5``807would return ``5`` for the value ``10``, or ``0`` for the value ``-1``.808When using :class:`FloatRange`, ``clamp`` can only be enabled if both809bounds are *closed* (the default).810811.. click:example::812813    @click.command()814    @click.option("--count", type=click.IntRange(0, 20, clamp=True))815    @click.option("--digit", type=click.IntRange(0, 9))816    def repeat(count, digit):817        click.echo(str(digit) * count)818819.. click:run::820821    invoke(repeat, args=['--count=100', '--digit=5'])822    invoke(repeat, args=['--count=6', '--digit=12'])823824825Callbacks for Validation826------------------------827828.. versionchanged:: 2.0829830If you want to apply custom validation logic, you can do this in the831parameter callbacks. These callbacks can both modify values as well as832raise errors if the validation does not work. The callback runs after833type conversion. It is called for all sources, including prompts.834835In Click 1.0, you can only raise the :exc:`UsageError` but starting with836Click 2.0, you can also raise the :exc:`BadParameter` error, which has the837added advantage that it will automatically format the error message to838also contain the parameter name.839840.. click:example::841842    def validate_rolls(ctx, param, value):843        if isinstance(value, tuple):844            return value845846        try:847            rolls, _, dice = value.partition("d")848            return int(dice), int(rolls)849        except ValueError:850            raise click.BadParameter("format must be 'NdM'")851852    @click.command()853    @click.option(854        "--rolls", type=click.UNPROCESSED, callback=validate_rolls,855        default="1d6", prompt=True,856    )857    def roll(rolls):858        sides, times = rolls859        click.echo(f"Rolling a {sides}-sided dice {times} time(s)")860861.. click:run::862863    invoke(roll, args=["--rolls=42"])864    println()865    invoke(roll, args=["--rolls=2d12"])866    println()867    invoke(roll, input=["42", "2d12"])868869870.. _optional-value:871872Optional Value873--------------874875Providing the value to an option can be made optional, in which case876providing only the option's flag without a value will either show a877prompt or use its ``flag_value``.878879Setting ``is_flag=False, flag_value=value`` tells Click that the option880can still be passed a value, but if only the flag is given the881``flag_value`` is used.882883.. click:example::884885    @click.command()886    @click.option("--name", is_flag=False, flag_value="Flag", default="Default")887    def hello(name):888        click.echo(f"Hello, {name}!")889890.. click:run::891892    invoke(hello, args=[])893    invoke(hello, args=["--name", "Value"])894    invoke(hello, args=["--name"])895896If the option has ``prompt`` enabled, then setting897``prompt_required=False`` tells Click to only show the prompt if the898option's flag is given, instead of if the option is not provided at all.899900.. click:example::901902    @click.command()903    @click.option('--name', prompt=True, prompt_required=False, default="Default")904    def hello(name):905        click.echo(f"Hello {name}!")906907.. click:run::908909    invoke(hello)910    invoke(hello, args=["--name", "Value"])911    invoke(hello, args=["--name"], input="Prompt")912913If ``required=True``, then the option will still prompt if it is not914given, but it will also prompt if only the flag is given.