Skip to content
Myr

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 file

Take it

The walk stopped after 200 commits: lines older than 1e054e0 point at it.

start version 8.0David Lordbefore adoption1e054e0

lines 1–87why, one step back
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):

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 88why, one step back
88 click.echo(f"from {from_} to {to}")

start version 8.0David Lordbefore adoption1e054e0

lines 89–111why, one step back
89
90And 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'])111

Merge pull request #1998 from MLH-Fellowship/1971-hide-defaultsDavid Lordbefore adoption5d759e0

lines 112–132why, one step back
112For single option boolean flags, the default remains hidden if the default
113value 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'])131132

start version 8.0David Lordbefore adoption1e054e0

lines 133–144why, one step back
133Multi Value Options
134-------------------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):

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

lines 145–146why, one step back
145 a, b = pos
146 click.echo(f"{a} / {b}")

start version 8.0David Lordbefore adoption1e054e0

lines 147–170why, one step back
147
148And 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):

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

lines 171–172why, one step back
171 name, id = item
172 click.echo(f"name={name} id={id}")

start version 8.0David Lordbefore adoption1e054e0

lines 173–188why, one step back
173
174And 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):

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

lines 189–190why, one step back
189 name, id = item
190 click.echo(f"name={name} id={id}")

start version 8.0David Lordbefore adoption1e054e0

lines 191–238why, one step back
191
192.. _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):

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 239why, one step back
239 click.echo(f"Verbosity: {verbose}")

start version 8.0David Lordbefore adoption1e054e0

lines 240–276why, one step back
240
241And 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'])

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

line 277why, one step back
277 invoke(info)

start version 8.0David Lordbefore adoption1e054e0

lines 278–298why, one step back
278
279If 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'])

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

line 299why, one step back
299 invoke(info)

start version 8.0David Lordbefore adoption1e054e0

lines 300–309why, one step back
300
301Note 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):

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 310why, one step back
310 click.echo(f"debug={debug}")

start version 8.0David Lordbefore adoption1e054e0

lines 311–411why, one step back
311
312 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.1

Merge branch '7.x'David Lordbefore adoptionbce4ea4

line 412why, one step back
412 The resulting value from an option will always be one of the

start version 8.0David Lordbefore adoption1e054e0

lines 413–430why, one step back
413 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):

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 431why, one step back
431 click.echo(f"Hello {name}!")

start version 8.0David Lordbefore adoption1e054e0

lines 432–447why, one step back
432
433And 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):

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 448why, one step back
448 click.echo(f"Hello {name}!")

start version 8.0David Lordbefore adoption1e054e0

lines 449–458why, one step back
449
450What 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.458

Merge pull request #1618 from MLH-Fellowship/prompt-requiredDavid Lordbefore adoption8efb348

lines 459–461why, one step back
459By default, the user will be prompted for an input if one was not passed
460through the command line. To turn this behavior off, see461:ref:`optional-value`.

start version 8.0David Lordbefore adoption1e054e0

line 462why, one step back
462

Merge pull request #1618 from MLH-Fellowship/prompt-requiredDavid Lordbefore adoption8efb348

line 463why, one step back
463

start version 8.0David Lordbefore adoption1e054e0

lines 464–471why, one step back
464Password Prompts
465----------------466467Click also supports hidden prompts and asking for confirmation. This is468useful for password input:469470.. click:example::471

Merge pull request #1783 from pallets/fix-docs-examplesDavid Lordbefore adoptionea3bb6f

lines 472–473why, one step back
472 import codecs
473

start version 8.0David Lordbefore adoption1e054e0

line 474why, one step back
474 @click.command()

Merge pull request #1783 from pallets/fix-docs-examplesDavid Lordbefore adoptionea3bb6f

lines 475–480why, one step back
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')}")

start version 8.0David Lordbefore adoption1e054e0

lines 481–483why, one step back
481
482.. click:run::483

Merge pull request #1783 from pallets/fix-docs-examplesDavid Lordbefore adoptionea3bb6f

line 484why, one step back
484 invoke(encode, input=['secret', 'secret'])

start version 8.0David Lordbefore adoption1e054e0

lines 485–488why, one step back
485
486Because this combination of parameters is quite common, this can also be487replaced with the :func:`password_option` decorator:488

Merge pull request #1783 from pallets/fix-docs-examplesDavid Lordbefore adoptionea3bb6f

line 489why, one step back
489.. code-block:: python

start version 8.0David Lordbefore adoption1e054e0

lines 490–493why, one step back
490
491 @click.command()492 @click.password_option()493 def encrypt(password):

Merge pull request #1783 from pallets/fix-docs-examplesDavid Lordbefore adoptionea3bb6f

line 494why, one step back
494 click.echo(f"encoded: to {codecs.encode(password, 'rot13')}")

start version 8.0David Lordbefore adoption1e054e0

line 495why, one step back
495

Merge pull request #1783 from pallets/fix-docs-examplesDavid Lordbefore adoptionea3bb6f

line 496why, one step back
496

start version 8.0David Lordbefore adoption1e054e0

lines 497–509why, one step back
497Dynamic Defaults for Prompts
498----------------------------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:509

Merge pull request #1783 from pallets/fix-docs-examplesDavid Lordbefore adoptionea3bb6f

line 510why, one step back
510.. code-block:: python

start version 8.0David Lordbefore adoption1e054e0

line 511why, one step back
511

Merge pull request #1783 from pallets/fix-docs-examplesDavid Lordbefore adoptionea3bb6f

lines 512–513why, one step back
512 import os
513

start version 8.0David Lordbefore adoption1e054e0

line 514why, one step back
514 @click.command()

Merge pull request #1783 from pallets/fix-docs-examplesDavid Lordbefore adoptionea3bb6f

lines 515–518why, one step back
515 @click.option(
516 "--username", prompt=True,517 default=lambda: os.environ.get("USER", "")518 )

start version 8.0David Lordbefore adoption1e054e0

line 519why, one step back
519 def hello(username):

Merge pull request #1783 from pallets/fix-docs-examplesDavid Lordbefore adoptionea3bb6f

line 520why, one step back
520 click.echo(f"Hello, {username}!")

start version 8.0David Lordbefore adoption1e054e0

lines 521–525why, one step back
521
522To describe what the default value will be, set it in ``show_default``.523524.. click:example::525

Merge pull request #1783 from pallets/fix-docs-examplesDavid Lordbefore adoptionea3bb6f

lines 526–527why, one step back
526 import os
527

start version 8.0David Lordbefore adoption1e054e0

line 528why, one step back
528 @click.command()

Merge pull request #1783 from pallets/fix-docs-examplesDavid Lordbefore adoptionea3bb6f

lines 529–533why, one step back
529 @click.option(
530 "--username", prompt=True,531 default=lambda: os.environ.get("USER", ""),532 show_default="current user"533 )

start version 8.0David Lordbefore adoption1e054e0

line 534why, one step back
534 def hello(username):

Merge pull request #1783 from pallets/fix-docs-examplesDavid Lordbefore adoptionea3bb6f

line 535why, one step back
535 click.echo(f"Hello, {username}!")

start version 8.0David Lordbefore adoption1e054e0

lines 536–538why, one step back
536
537.. click:run::538

Merge pull request #1783 from pallets/fix-docs-examplesDavid Lordbefore adoptionea3bb6f

line 539why, one step back
539 invoke(hello, args=["--help"])

start version 8.0David Lordbefore adoption1e054e0

line 540why, one step back
540

Merge pull request #1783 from pallets/fix-docs-examplesDavid Lordbefore adoptionea3bb6f

line 541why, one step back
541

start version 8.0David Lordbefore adoption1e054e0

lines 542–669why, one step back
542Callbacks and Eager Options
543---------------------------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):

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 670why, one step back
670 click.echo(f'Hello {username}!')

start version 8.0David Lordbefore adoption1e054e0

lines 671–694why, one step back
671
672 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):

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 695why, one step back
695 click.echo(f"Debug mode is {'on' if debug else 'off'}")

start version 8.0David Lordbefore adoption1e054e0

lines 696–699why, one step back
696
697 @cli.command()698 @click.option('--username')699 def greet(username):

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 700why, one step back
700 click.echo(f"Hello {username}!")

start version 8.0David Lordbefore adoption1e054e0

lines 701–721why, one step back
701
702 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):

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 722why, one step back
722 click.echo(f"Hello {username}!")

start version 8.0David Lordbefore adoption1e054e0

lines 723–770why, one step back
723
724 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 os

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 771why, one step back
771 invoke(perform, env={"PATHS": f"./foo/bar{os.path.pathsep}./test"})

start version 8.0David Lordbefore adoption1e054e0

lines 772–786why, one step back
772
773Other 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):

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 787why, one step back
787 click.echo(f"writable={w}")

start version 8.0David Lordbefore adoption1e054e0

lines 788–806why, one step back
788
789 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):

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

line 807why, one step back
807 click.echo(f"debug={debug}")

start version 8.0David Lordbefore adoption1e054e0

lines 808–816why, one step back
808
809 if __name__ == '__main__':810 log()811812.. _ranges:813814Range Options815-------------816

Merge pull request #1303 from robintully/issue_1110_open_intervalDavid Lordbefore adoptionca75bab

lines 817–819why, one step back
817The :class:`IntRange` type extends the :data:`INT` type to ensure the
818value is contained in the given range. The :class:`FloatRange` type does819the same for :data:`FLOAT`.

start version 8.0David Lordbefore adoption1e054e0

line 820why, one step back
820

Merge pull request #1303 from robintully/issue_1110_open_intervalDavid Lordbefore adoptionca75bab

lines 821–824why, one step back
821If ``min`` or ``max`` is omitted, that side is *unbounded*. Any value in
822that 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.

start version 8.0David Lordbefore adoption1e054e0

line 825why, one step back
825

Merge pull request #1303 from robintully/issue_1110_open_intervalDavid Lordbefore adoptionca75bab

lines 826–830why, one step back
826If ``clamp`` mode is enabled, a value that is outside the range is set
827to 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).

start version 8.0David Lordbefore adoption1e054e0

lines 831–834why, one step back
831
832.. click:example::833834 @click.command()

Merge pull request #1303 from robintully/issue_1110_open_intervalDavid Lordbefore adoptionca75bab

lines 835–836why, one step back
835 @click.option("--count", type=click.IntRange(0, 20, clamp=True))
836 @click.option("--digit", type=click.IntRange(0, 9))

start version 8.0David Lordbefore adoption1e054e0

lines 837–841why, one step back
837 def repeat(count, digit):
838 click.echo(str(digit) * count)839840.. click:run::841

Merge pull request #1303 from robintully/issue_1110_open_intervalDavid Lordbefore adoptionca75bab

lines 842–843why, one step back
842 invoke(repeat, args=['--count=100', '--digit=5'])
843 invoke(repeat, args=['--count=6', '--digit=12'])

start version 8.0David Lordbefore adoption1e054e0

lines 844–851why, one step back
844
845846Callbacks for Validation847------------------------848849.. versionchanged:: 2.0850851If you want to apply custom validation logic, you can do this in the

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

lines 852–854why, one step back
852parameter callbacks. These callbacks can both modify values as well as
853raise errors if the validation does not work. The callback runs after854type conversion. It is called for all sources, including prompts.

start version 8.0David Lordbefore adoption1e054e0

lines 855–863why, one step back
855
856In 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):

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

lines 864–866why, one step back
864 if isinstance(value, tuple):
865 return value866

start version 8.0David Lordbefore adoption1e054e0

line 867why, one step back
867 try:

Merge pull request #1783 from pallets/fix-docs-examplesDavid Lordbefore adoptionea3bb6f

lines 868–869why, one step back
868 rolls, _, dice = value.partition("d")
869 return int(dice), int(rolls)

start version 8.0David Lordbefore adoption1e054e0

line 870why, one step back
870 except ValueError:

Merge pull request #1783 from pallets/fix-docs-examplesDavid Lordbefore adoptionea3bb6f

line 871why, one step back
871 raise click.BadParameter("format must be 'NdM'")

start version 8.0David Lordbefore adoption1e054e0

lines 872–873why, one step back
872
873 @click.command()

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

lines 874–877why, one step back
874 @click.option(
875 "--rolls", type=click.UNPROCESSED, callback=validate_rolls,876 default="1d6", prompt=True,877 )

start version 8.0David Lordbefore adoption1e054e0

line 878why, one step back
878 def roll(rolls):

Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9

lines 879–880why, one step back
879 sides, times = rolls
880 click.echo(f"Rolling a {sides}-sided dice {times} time(s)")

start version 8.0David Lordbefore adoption1e054e0

lines 881–883why, one step back
881
882.. click:run::883

Merge pull request #1783 from pallets/fix-docs-examplesDavid Lordbefore adoptionea3bb6f

line 884why, one step back
884 invoke(roll, args=["--rolls=42"])

start version 8.0David Lordbefore adoption1e054e0

line 885why, one step back
885 println()

Merge pull request #1783 from pallets/fix-docs-examplesDavid Lordbefore adoptionea3bb6f

line 886why, one step back
886 invoke(roll, args=["--rolls=2d12"])

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

lines 887–888why, one step back
887 println()
888 invoke(roll, input=["42", "2d12"])

Merge pull request #1618 from MLH-Fellowship/prompt-requiredDavid Lordbefore adoption8efb348

lines 889–935why, one step back
889
890891.. _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.