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 fileTake it
The walk stopped after 200 commits: lines older than 5210849 point at it.
Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 1–12why, one step back1.. _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>`.12Merge pull request #1016 from dawran6/issue-725Dan Sullybefore adoptionc914686
lines 13–15why, one step back13Name Your Options14-----------------15Merge branch '7.x'David Lordbefore adoption8f36eab
lines 16–19why, one step back16Options 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.Merge pull request #1016 from dawran6/issue-725Dan Sullybefore adoptionc914686
line 20why, one step back20Merge branch '7.x'David Lordbefore adoption8f36eab
line 21why, one step back21A name is chosen in the following orderMerge pull request #1016 from dawran6/issue-725Dan Sullybefore adoptionc914686
line 22why, one step back22Merge branch '7.x'David Lordbefore adoption8f36eab
lines 23–34why, one step back231. 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:: python34Merge pull request #1016 from dawran6/issue-725Dan Sullybefore adoptionc914686
lines 35–39why, one step back35 @click.command()36 @click.option('-s', '--string-to-echo')37 def echo(string_to_echo):38 click.echo(string_to_echo)39Merge branch '7.x'David Lordbefore adoption8f36eab
line 40why, one step back40.. code-block:: pythonMerge pull request #1016 from dawran6/issue-725Dan Sullybefore adoptionc914686
lines 41–45why, one step back4142 @click.command()43 @click.option('-s', '--string-to-echo', 'string')44 def echo(string):45 click.echo(string)Merge branch '7.x'David Lordbefore adoption8f36eab
lines 46–53why, one step back4647- ``"-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``Merge pull request #1016 from dawran6/issue-725Dan Sullybefore adoptionc914686
line 54why, one step back54Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 55–62why, one step back55Basic 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 isMerge pull request #1022 from pallets/514-document-requiredDan Sullybefore adoptionb10c52a
lines 63–64why, one step back63used. By default, options are not required, however to make an option required,64simply pass in `required=True` as an argument to the decorator.Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 65–69why, one step back6566.. click:example::6768 @click.command()69 @click.option('--n', default=1)Merge pull request #1022 from pallets/514-document-requiredDan Sullybefore adoptionb10c52a
lines 70–77why, one step back70 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)Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 78–84why, one step back78 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()Follow PEP8 recommendation for param naming (#1073)Renne Rochabefore adoption03e0133
line 85why, one step back85 @click.option('--from', '-f', 'from_')Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
line 86why, one step back86 @click.option('--to', '-t')Follow PEP8 recommendation for param naming (#1073)Renne Rochabefore adoption03e0133
line 87why, one step back87 def reserved_param_name(from_, to):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 88why, one step back88 click.echo(f"from {from_} to {to}")Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 89–98why, one step back8990And 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.98Merge pull request #996 from dougharris/lambda-844-547Dan Sullybefore adoptionbc53a96
lines 99–111why, one step back99To 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'])111Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 112–123why, one step back112Multi 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):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
lines 124–125why, one step back124 a, b = pos125 click.echo(f"{a} / {b}")Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 126–147why, one step back126127And 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()Merge pull request #1100 from pallets/sphinxDavid Lordbefore adoptionb1b8c48
line 148why, one step back148 @click.option('--item', type=(str, int))Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
line 149why, one step back149 def putitem(item):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
lines 150–151why, one step back150 name, id = item151 click.echo(f"name={name} id={id}")Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 152–165why, one step back152153And 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()Merge pull request #1100 from pallets/sphinxDavid Lordbefore adoptionb1b8c48
line 166why, one step back166 @click.option('--item', nargs=2, type=click.Tuple([str, int]))Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
line 167why, one step back167 def putitem(item):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
lines 168–169why, one step back168 name, id = item169 click.echo(f"name={name} id={id}")Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
line 170why, one step back170Merge branch '7.x'David Lordbefore adoptionc6ef735
lines 171–172why, one step back171.. _multiple-options:172Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 173–176why, one step back173Multiple Options174----------------175176Similarly to ``nargs``, there is also the case of wanting to support aMerge branch '7.x'David Lordbefore adoption2269786
line 177why, one step back177parameter being provided multiple times and have all the values recorded --Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 178–196why, one step back178not 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'])196Merge branch '7.x'David Lordbefore adoption2269786
lines 197–205why, one step back197When 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"])204205Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 206–217why, one step back206Counting207--------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):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 218why, one step back218 click.echo(f"Verbosity: {verbose}")Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 219–286why, one step back219220And 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):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 287why, one step back287 click.echo(f"debug={debug}")Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 288–351why, one step back288289 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 instantiatedMerge branch '7.x'David Lordbefore adoption11abf2b
lines 352–354why, one step back352with 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.Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 355–360why, one step back355356Example:357358.. click:example::359360 @click.command()Merge branch '7.x'David Lordbefore adoption11abf2b
lines 361–362why, one step back361 @click.option('--hash-type',362 type=click.Choice(['MD5', 'SHA1'], case_sensitive=False))Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 363–369why, one step back363 def digest(hash_type):364 click.echo(hash_type)365366What it looks like:367368.. click:run::369Merge branch '7.x'David Lordbefore adoption11abf2b
lines 370–371why, one step back370 invoke(digest, args=['--hash-type=MD5'])371 println()Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 372–377why, one step back372 invoke(digest, args=['--hash-type=md5'])373 println()374 invoke(digest, args=['--hash-type=foo'])375 println()376 invoke(digest, args=['--help'])377Merge branch '7.x'David Lordbefore adoption2269786
lines 378–379why, one step back378Only pass the choices as list or tuple. Other iterables (like379generators) may lead to unexpected results.Improve docs for Choice type (addresses issue #892) (#900)Stefan Scherfkebefore adoptionc67daae
line 380why, one step back380Merge branch '7.x'David Lordbefore adoption2269786
lines 381–383why, one step back381Choices 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.Merge branch '7.x'David Lordbefore adoption11abf2b
line 384why, one step back384Merge branch '7.x'David Lordbefore adoption2269786
lines 385–386why, one step back385Choices should be unique after considering the effects of386``case_sensitive`` and any specified token normalization function.Improve docs for Choice type (addresses issue #892) (#900)Stefan Scherfkebefore adoptionc67daae
line 387why, one step back387Merge branch '7.x'David Lordbefore adoption6944450
line 388why, one step back388.. versionchanged:: 7.1Merge branch '7.x'David Lordbefore adoptionbce4ea4
line 389why, one step back389 The resulting value from an option will always be one of theMerge branch '7.x'David Lordbefore adoption6944450
lines 390–391why, one step back390 originally passed choices regardless of ``case_sensitive``.391Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 392–407why, one step back392.. _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):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 408why, one step back408 click.echo(f"Hello {name}!")Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 409–424why, one step back409410And 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):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 425why, one step back425 click.echo(f"Hello {name}!")Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 426–431why, one step back426427What it looks like:428429.. click:run::430431 invoke(hello, input=['John'])Merge branch '7.x'David Lordbefore adoption2269786
lines 432–435why, one step back432433It is advised that prompt not be used in conjunction with the multiple434flag set to True. Instead, prompt in the function interactively.435Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 436–448why, one step back436437Password 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):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 449why, one step back449 click.echo(f"Encrypting password to {password.encode('rot13')}")Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 450–464why, one step back450451What 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):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 465why, one step back465 click.echo(f"Encrypting password to {password.encode('rot13')}")Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 466–486why, one step back466467Dynamic 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)Merge pull request #996 from dougharris/lambda-844-547Dan Sullybefore adoptionbc53a96
lines 487–501why, one step back487488To 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'])Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 502–620why, one step back502503Callbacks 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 subcommandMerge branch '7.x'David Lordbefore adoption8b971f7
lines 621–622why, one step back621called ``run`` taking an option called ``reload`` and the prefix is622``WEB``, then the variable is ``WEB_RUN_RELOAD``.Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 623–630why, one step back623624Example usage:625626.. click:example::627628 @click.command()629 @click.option('--username')630 def greet(username):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 631why, one step back631 click.echo(f'Hello {username}!')Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 632–642why, one step back632633 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')642Merge branch '7.x'David Lordbefore adoption8b971f7
lines 643–647why, one step back643When 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``.Merge pull request #1011 from dougharris/auto-envvar-501Dan Sullybefore adoption0650d36
lines 648–655why, one step back648649Example:650651.. click:example::652653 @click.group()654 @click.option('--debug/--no-debug')655 def cli(debug):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 656why, one step back656 click.echo(f"Debug mode is {'on' if debug else 'off'}")Merge pull request #1011 from dougharris/auto-envvar-501Dan Sullybefore adoption0650d36
lines 657–660why, one step back657658 @cli.command()659 @click.option('--username')660 def greet(username):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 661why, one step back661 click.echo(f"Hello {username}!")Merge pull request #1011 from dougharris/auto-envvar-501Dan Sullybefore adoption0650d36
lines 662–672why, one step back662663 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')671672Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 673–682why, one step back673The 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):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 683why, one step back683 click.echo(f"Hello {username}!")Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 684–731why, one step back684685 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 osMerge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 732why, one step back732 invoke(perform, env={"PATHS": f"./foo/bar{os.path.pathsep}./test"})Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 733–747why, one step back733734Other 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):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 748why, one step back748 click.echo(f"writable={w}")Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 749–767why, one step back749750 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):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 768why, one step back768 click.echo(f"debug={debug}")Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 769–839why, one step back769770 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):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
lines 840–841why, one step back840 sides, times = rolls841 click.echo(f"Rolling a {sides}-sided dice {times} time(s)")Merge pull request #806 from stopthatcow/feature/790Markus Unterwaditzerbefore adoption5210849
lines 842–852why, one step back842843 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'])