options.rst
This file
Path
docs/options.rst
935 lines · 26.1 KiB
Last changed by
Merge pull request #1998 from MLH-Fellowship/1971-hide-defaultsDavid Lordbefore adoption5d759e0
History of this fileTake 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 two parameters: the current563:class:`Context` and the value. The context provides some useful features564such as quitting the application and gives access to other already565processed parameters.566567Here 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'])596597.. admonition:: Callback Signature Changes598599 In Click 2.0 the signature for callbacks changed. For more600 information about these changes see :ref:`upgrade-to-2.0`.601602Yes Parameters603--------------604605For dangerous operations, it's very useful to be able to ask a user for606confirmation. This can be done by adding a boolean ``--yes`` flag and607asking for confirmation if the user did not provide it and to fail in a608callback:609610.. click:example::611612 def abort_if_false(ctx, param, value):613 if not value:614 ctx.abort()615616 @click.command()617 @click.option('--yes', is_flag=True, callback=abort_if_false,618 expose_value=False,619 prompt='Are you sure you want to drop the db?')620 def dropdb():621 click.echo('Dropped all tables!')622623And what it looks like on the command line:624625.. click:run::626627 invoke(dropdb, input=['n'])628 invoke(dropdb, args=['--yes'])629630Because this combination of parameters is quite common, this can also be631replaced with the :func:`confirmation_option` decorator:632633.. click:example::634635 @click.command()636 @click.confirmation_option(prompt='Are you sure you want to drop the db?')637 def dropdb():638 click.echo('Dropped all tables!')639640.. admonition:: Callback Signature Changes641642 In Click 2.0 the signature for callbacks changed. For more643 information about these changes see :ref:`upgrade-to-2.0`.644645Values from Environment Variables646---------------------------------647648A very useful feature of Click is the ability to accept parameters from649environment variables in addition to regular parameters. This allows650tools to be automated much easier. For instance, you might want to pass651a configuration file with a ``--config`` parameter but also support exporting652a ``TOOL_CONFIG=hello.cfg`` key-value pair for a nicer development653experience.654655This is supported by Click in two ways. One is to automatically build656environment variables which is supported for options only. To enable this657feature, the ``auto_envvar_prefix`` parameter needs to be passed to the658script that is invoked. Each command and parameter is then added as an659uppercase underscore-separated variable. If you have a subcommand660called ``run`` taking an option called ``reload`` and the prefix is661``WEB``, then the variable is ``WEB_RUN_RELOAD``.662663Example usage:664665.. click:example::666667 @click.command()668 @click.option('--username')669 def greet(username):670 click.echo(f'Hello {username}!')671672 if __name__ == '__main__':673 greet(auto_envvar_prefix='GREETER')674675And from the command line:676677.. click:run::678679 invoke(greet, env={'GREETER_USERNAME': 'john'},680 auto_envvar_prefix='GREETER')681682When using ``auto_envvar_prefix`` with command groups, the command name683needs to be included in the environment variable, between the prefix and684the parameter name, *i.e.* ``PREFIX_COMMAND_VARIABLE``. If you have a685subcommand called ``run-server`` taking an option called ``host`` and686the prefix is ``WEB``, then the variable is ``WEB_RUN_SERVER_HOST``.687688Example:689690.. click:example::691692 @click.group()693 @click.option('--debug/--no-debug')694 def cli(debug):695 click.echo(f"Debug mode is {'on' if debug else 'off'}")696697 @cli.command()698 @click.option('--username')699 def greet(username):700 click.echo(f"Hello {username}!")701702 if __name__ == '__main__':703 cli(auto_envvar_prefix='GREETER')704705.. click:run::706707 invoke(cli, args=['greet',],708 env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},709 auto_envvar_prefix='GREETER')710711712The second option is to manually pull values in from specific environment713variables by defining the name of the environment variable on the option.714715Example usage:716717.. click:example::718719 @click.command()720 @click.option('--username', envvar='USERNAME')721 def greet(username):722 click.echo(f"Hello {username}!")723724 if __name__ == '__main__':725 greet()726727And from the command line:728729.. click:run::730731 invoke(greet, env={'USERNAME': 'john'})732733In that case it can also be a list of different environment variables734where the first one is picked.735736Multiple Values from Environment Values737---------------------------------------738739As options can accept multiple values, pulling in such values from740environment variables (which are strings) is a bit more complex. The way741Click solves this is by leaving it up to the type to customize this742behavior. For both ``multiple`` and ``nargs`` with values other than743``1``, Click will invoke the :meth:`ParamType.split_envvar_value` method to744perform the splitting.745746The default implementation for all types is to split on whitespace. The747exceptions to this rule are the :class:`File` and :class:`Path` types748which both split according to the operating system's path splitting rules.749On Unix systems like Linux and OS X, the splitting happens for those on750every colon (``:``), and for Windows, on every semicolon (``;``).751752Example usage:753754.. click:example::755756 @click.command()757 @click.option('paths', '--path', envvar='PATHS', multiple=True,758 type=click.Path())759 def perform(paths):760 for path in paths:761 click.echo(path)762763 if __name__ == '__main__':764 perform()765766And from the command line:767768.. click:run::769770 import os771 invoke(perform, env={"PATHS": f"./foo/bar{os.path.pathsep}./test"})772773Other Prefix Characters774-----------------------775776Click can deal with alternative prefix characters other than ``-`` for777options. This is for instance useful if you want to handle slashes as778parameters ``/`` or something similar. Note that this is strongly779discouraged in general because Click wants developers to stay close to780POSIX semantics. However in certain situations this can be useful:781782.. click:example::783784 @click.command()785 @click.option('+w/-w')786 def chmod(w):787 click.echo(f"writable={w}")788789 if __name__ == '__main__':790 chmod()791792And from the command line:793794.. click:run::795796 invoke(chmod, args=['+w'])797 invoke(chmod, args=['-w'])798799Note that if you are using ``/`` as prefix character and you want to use a800boolean flag you need to separate it with ``;`` instead of ``/``:801802.. click:example::803804 @click.command()805 @click.option('/debug;/no-debug')806 def log(debug):807 click.echo(f"debug={debug}")808809 if __name__ == '__main__':810 log()811812.. _ranges:813814Range Options815-------------816817The :class:`IntRange` type extends the :data:`INT` type to ensure the818value is contained in the given range. The :class:`FloatRange` type does819the same for :data:`FLOAT`.820821If ``min`` or ``max`` is omitted, that side is *unbounded*. Any value in822that direction is accepted. By default, both bounds are *closed*, which823means the boundary value is included in the accepted range. ``min_open``824and ``max_open`` can be used to exclude that boundary from the range.825826If ``clamp`` mode is enabled, a value that is outside the range is set827to the boundary instead of failing. For example, the range ``0, 5``828would return ``5`` for the value ``10``, or ``0`` for the value ``-1``.829When using :class:`FloatRange`, ``clamp`` can only be enabled if both830bounds are *closed* (the default).831832.. click:example::833834 @click.command()835 @click.option("--count", type=click.IntRange(0, 20, clamp=True))836 @click.option("--digit", type=click.IntRange(0, 9))837 def repeat(count, digit):838 click.echo(str(digit) * count)839840.. click:run::841842 invoke(repeat, args=['--count=100', '--digit=5'])843 invoke(repeat, args=['--count=6', '--digit=12'])844845846Callbacks for Validation847------------------------848849.. versionchanged:: 2.0850851If you want to apply custom validation logic, you can do this in the852parameter callbacks. These callbacks can both modify values as well as853raise errors if the validation does not work. The callback runs after854type conversion. It is called for all sources, including prompts.855856In Click 1.0, you can only raise the :exc:`UsageError` but starting with857Click 2.0, you can also raise the :exc:`BadParameter` error, which has the858added advantage that it will automatically format the error message to859also contain the parameter name.860861.. click:example::862863 def validate_rolls(ctx, param, value):864 if isinstance(value, tuple):865 return value866867 try:868 rolls, _, dice = value.partition("d")869 return int(dice), int(rolls)870 except ValueError:871 raise click.BadParameter("format must be 'NdM'")872873 @click.command()874 @click.option(875 "--rolls", type=click.UNPROCESSED, callback=validate_rolls,876 default="1d6", prompt=True,877 )878 def roll(rolls):879 sides, times = rolls880 click.echo(f"Rolling a {sides}-sided dice {times} time(s)")881882.. click:run::883884 invoke(roll, args=["--rolls=42"])885 println()886 invoke(roll, args=["--rolls=2d12"])887 println()888 invoke(roll, input=["42", "2d12"])889890891.. _optional-value:892893Optional Value894--------------895896Providing the value to an option can be made optional, in which case897providing only the option's flag without a value will either show a898prompt or use its ``flag_value``.899900Setting ``is_flag=False, flag_value=value`` tells Click that the option901can still be passed a value, but if only the flag is given the902``flag_value`` is used.903904.. click:example::905906 @click.command()907 @click.option("--name", is_flag=False, flag_value="Flag", default="Default")908 def hello(name):909 click.echo(f"Hello, {name}!")910911.. click:run::912913 invoke(hello, args=[])914 invoke(hello, args=["--name", "Value"])915 invoke(hello, args=["--name"])916917If the option has ``prompt`` enabled, then setting918``prompt_required=False`` tells Click to only show the prompt if the919option's flag is given, instead of if the option is not provided at all.920921.. click:example::922923 @click.command()924 @click.option('--name', prompt=True, prompt_required=False, default="Default")925 def hello(name):926 click.echo(f"Hello {name}!")927928.. click:run::929930 invoke(hello)931 invoke(hello, args=["--name", "Value"])932 invoke(hello, args=["--name"], input="Prompt")933934If ``required=True``, then the option will still prompt if it is not935given, but it will also prompt if only the flag is given.