Skip to content
Myr

options.rst

This file

Path

docs/options.rst

826 lines · 22.8 KiB

Last changed by

prevent automatic environment variables from containing dashesGregory Pakoszbefore adoption91ea0de

History of this file

Take it

1.. _options:23Options4=======56.. currentmodule:: click78Adding options to commands can be accomplished by the :func:`option`9decorator.  Since options can come in various different versions, there10are a ton of parameters to configure their behavior. Options in click are11distinct from :ref:`positional arguments <arguments>`.1213Name Your Options14-----------------1516The naming rules can be found in :ref:`parameter_names`. In short, you17can refer the option **implicitly** by the longest dash-prefixed argument:1819.. click:example::2021    @click.command()22    @click.option('-s', '--string-to-echo')23    def echo(string_to_echo):24        click.echo(string_to_echo)2526Or, **explicitly**, by giving one non-dash-prefixed argument:2728.. click:example::2930    @click.command()31    @click.option('-s', '--string-to-echo', 'string')32    def echo(string):33        click.echo(string)3435Basic Value Options36-------------------3738The most basic option is a value option.  These options accept one39argument which is a value.  If no type is provided, the type of the default40value is used.  If no default value is provided, the type is assumed to be41:data:`STRING`.  Unless a name is explicitly specified, the name of the42parameter is the first long option defined; otherwise the first short one is43used. By default, options are not required, however to make an option required,44simply pass in `required=True` as an argument to the decorator.4546.. click:example::4748    @click.command()49    @click.option('--n', default=1)50    def dots(n):51        click.echo('.' * n)5253.. click:example::5455    # How to make an option required56    @click.command()57    @click.option('--n', required=True, type=int)58    def dots(n):59        click.echo('.' * n)6061.. click:example::6263    # How to use a Python reserved word such as `from` as a parameter64    @click.command()65    @click.option('--from', '-f', 'from_')66    @click.option('--to', '-t')67    def reserved_param_name(from_, to):68        click.echo('from %s to %s' % (from_, to))6970And on the command line:7172.. click:run::7374   invoke(dots, args=['--n=2'])7576In this case the option is of type :data:`INT` because the default value77is an integer.7879To show the default values when showing command help, use ``show_default=True``8081.. click:example::8283    @click.command()84    @click.option('--n', default=1, show_default=True)85    def dots(n):86        click.echo('.' * n)8788.. click:run::8990   invoke(dots, args=['--help'])9192Multi Value Options93-------------------9495Sometimes, you have options that take more than one argument.  For options,96only a fixed number of arguments is supported.  This can be configured by97the ``nargs`` parameter.  The values are then stored as a tuple.9899.. click:example::100101    @click.command()102    @click.option('--pos', nargs=2, type=float)103    def findme(pos):104        click.echo('%s / %s' % pos)105106And on the command line:107108.. click:run::109110    invoke(findme, args=['--pos', '2.0', '3.0'])111112.. _tuple-type:113114Tuples as Multi Value Options115-----------------------------116117.. versionadded:: 4.0118119As you can see that by using `nargs` set to a specific number each item in120the resulting tuple is of the same type.  This might not be what you want.121Commonly you might want to use different types for different indexes in122the tuple.  For this you can directly specify a tuple as type:123124.. click:example::125126    @click.command()127    @click.option('--item', type=(str, int))128    def putitem(item):129        click.echo('name=%s id=%d' % item)130131And on the command line:132133.. click:run::134135    invoke(putitem, args=['--item', 'peter', '1338'])136137By using a tuple literal as type, `nargs` gets automatically set to the138length of the tuple and the :class:`click.Tuple` type is automatically139used.  The above example is thus equivalent to this:140141.. click:example::142143    @click.command()144    @click.option('--item', nargs=2, type=click.Tuple([str, int]))145    def putitem(item):146        click.echo('name=%s id=%d' % item)147148Multiple Options149----------------150151Similarly to ``nargs``, there is also the case of wanting to support a152parameter being provided multiple times and have all the values recorded --153not just the last one.  For instance, ``git commit -m foo -m bar`` would154record two lines for the commit message: ``foo`` and ``bar``. This can be155accomplished with the ``multiple`` flag:156157Example:158159.. click:example::160161    @click.command()162    @click.option('--message', '-m', multiple=True)163    def commit(message):164        click.echo('\n'.join(message))165166And on the command line:167168.. click:run::169170    invoke(commit, args=['-m', 'foo', '-m', 'bar'])171172When passing a ``default`` with ``multiple=True``, the default value173must be a list or tuple, otherwise it will be interpreted as a list of174single characters.175176.. code-block:: python177178    @click.option("--format", multiple=True, default=["json"])179180181Counting182--------183184In some very rare circumstances, it is interesting to use the repetition185of options to count an integer up.  This can be used for verbosity flags,186for instance:187188.. click:example::189190    @click.command()191    @click.option('-v', '--verbose', count=True)192    def log(verbose):193        click.echo('Verbosity: %s' % verbose)194195And on the command line:196197.. click:run::198199    invoke(log, args=['-vvv'])200201Boolean Flags202-------------203204Boolean flags are options that can be enabled or disabled.  This can be205accomplished by defining two flags in one go separated by a slash (``/``)206for enabling or disabling the option.  (If a slash is in an option string,207Click automatically knows that it's a boolean flag and will pass208``is_flag=True`` implicitly.)  Click always wants you to provide an enable209and disable flag so that you can change the default later.210211Example:212213.. click:example::214215    import sys216217    @click.command()218    @click.option('--shout/--no-shout', default=False)219    def info(shout):220        rv = sys.platform221        if shout:222            rv = rv.upper() + '!!!!111'223        click.echo(rv)224225And on the command line:226227.. click:run::228229    invoke(info, args=['--shout'])230    invoke(info, args=['--no-shout'])231232If you really don't want an off-switch, you can just define one and233manually inform Click that something is a flag:234235.. click:example::236237    import sys238239    @click.command()240    @click.option('--shout', is_flag=True)241    def info(shout):242        rv = sys.platform243        if shout:244            rv = rv.upper() + '!!!!111'245        click.echo(rv)246247And on the command line:248249.. click:run::250251    invoke(info, args=['--shout'])252253Note that if a slash is contained in your option already (for instance, if254you use Windows-style parameters where ``/`` is the prefix character), you255can alternatively split the parameters through ``;`` instead:256257.. click:example::258259    @click.command()260    @click.option('/debug;/no-debug')261    def log(debug):262        click.echo('debug=%s' % debug)263264    if __name__ == '__main__':265        log()266267.. versionchanged:: 6.0268269If you want to define an alias for the second option only, then you will270need to use leading whitespace to disambiguate the format string:271272Example:273274.. click:example::275276    import sys277278    @click.command()279    @click.option('--shout/--no-shout', ' /-S', default=False)280    def info(shout):281        rv = sys.platform282        if shout:283            rv = rv.upper() + '!!!!111'284        click.echo(rv)285286.. click:run::287288    invoke(info, args=['--help'])289290Feature Switches291----------------292293In addition to boolean flags, there are also feature switches.  These are294implemented by setting multiple options to the same parameter name and295defining a flag value.  Note that by providing the ``flag_value`` parameter,296Click will implicitly set ``is_flag=True``.297298To set a default flag, assign a value of `True` to the flag that should be299the default.300301.. click:example::302303    import sys304305    @click.command()306    @click.option('--upper', 'transformation', flag_value='upper',307                  default=True)308    @click.option('--lower', 'transformation', flag_value='lower')309    def info(transformation):310        click.echo(getattr(sys.platform, transformation)())311312And on the command line:313314.. click:run::315316    invoke(info, args=['--upper'])317    invoke(info, args=['--lower'])318    invoke(info)319320.. _choice-opts:321322Choice Options323--------------324325Sometimes, you want to have a parameter be a choice of a list of values.326In that case you can use :class:`Choice` type.  It can be instantiated327with a list of valid values.  The originally passed choice will be returned,328not the str passed on the command line.  Token normalization functions and329``case_sensitive=False`` can cause the two to be different but still match.330331Example:332333.. click:example::334335    @click.command()336    @click.option('--hash-type',337                  type=click.Choice(['MD5', 'SHA1'], case_sensitive=False))338    def digest(hash_type):339        click.echo(hash_type)340341What it looks like:342343.. click:run::344345    invoke(digest, args=['--hash-type=MD5'])346    println()347    invoke(digest, args=['--hash-type=md5'])348    println()349    invoke(digest, args=['--hash-type=foo'])350    println()351    invoke(digest, args=['--help'])352353Only pass the choices as list or tuple. Other iterables (like354generators) may lead to unexpected results.355356Choices work with options that have ``multiple=True``. If a ``default``357value is given with ``multiple=True``, it should be a list or tuple of358valid choices.359360Choices should be unique after considering the effects of361``case_sensitive`` and any specified token normalization function.362363.. versionchanged:: 7.1364    The resulting value from an option will always be on the of the365    originally passed choices regardless of ``case_sensitive``.366367.. _option-prompting:368369Prompting370---------371372In some cases, you want parameters that can be provided from the command line,373but if not provided, ask for user input instead.  This can be implemented with374Click by defining a prompt string.375376Example:377378.. click:example::379380    @click.command()381    @click.option('--name', prompt=True)382    def hello(name):383        click.echo('Hello %s!' % name)384385And what it looks like:386387.. click:run::388389    invoke(hello, args=['--name=John'])390    invoke(hello, input=['John'])391392If you are not happy with the default prompt string, you can ask for393a different one:394395.. click:example::396397    @click.command()398    @click.option('--name', prompt='Your name please')399    def hello(name):400        click.echo('Hello %s!' % name)401402What it looks like:403404.. click:run::405406    invoke(hello, input=['John'])407408It is advised that prompt not be used in conjunction with the multiple409flag set to True. Instead, prompt in the function interactively.410411412Password Prompts413----------------414415Click also supports hidden prompts and asking for confirmation.  This is416useful for password input:417418.. click:example::419420    @click.command()421    @click.option('--password', prompt=True, hide_input=True,422                  confirmation_prompt=True)423    def encrypt(password):424        click.echo('Encrypting password to %s' % password.encode('rot13'))425426What it looks like:427428.. click:run::429430    invoke(encrypt, input=['secret', 'secret'])431432Because this combination of parameters is quite common, this can also be433replaced with the :func:`password_option` decorator:434435.. click:example::436437    @click.command()438    @click.password_option()439    def encrypt(password):440        click.echo('Encrypting password to %s' % password.encode('rot13'))441442Dynamic Defaults for Prompts443----------------------------444445The ``auto_envvar_prefix`` and ``default_map`` options for the context446allow the program to read option values from the environment or a447configuration file.  However, this overrides the prompting mechanism, so448that the user does not get the option to change the value interactively.449450If you want to let the user configure the default value, but still be451prompted if the option isn't specified on the command line, you can do so452by supplying a callable as the default value. For example, to get a default453from the environment:454455.. click:example::456457    @click.command()458    @click.option('--username', prompt=True,459                  default=lambda: os.environ.get('USER', ''))460    def hello(username):461        print("Hello,", username)462463To describe what the default value will be, set it in ``show_default``.464465.. click:example::466467    @click.command()468    @click.option('--username', prompt=True,469                  default=lambda: os.environ.get('USER', ''),470                  show_default='current user')471    def hello(username):472        print("Hello,", username)473474.. click:run::475476   invoke(hello, args=['--help'])477478Callbacks and Eager Options479---------------------------480481Sometimes, you want a parameter to completely change the execution flow.482For instance, this is the case when you want to have a ``--version``483parameter that prints out the version and then exits the application.484485Note: an actual implementation of a ``--version`` parameter that is486reusable is available in Click as :func:`click.version_option`.  The code487here is merely an example of how to implement such a flag.488489In such cases, you need two concepts: eager parameters and a callback.  An490eager parameter is a parameter that is handled before others, and a491callback is what executes after the parameter is handled.  The eagerness492is necessary so that an earlier required parameter does not produce an493error message.  For instance, if ``--version`` was not eager and a494parameter ``--foo`` was required and defined before, you would need to495specify it for ``--version`` to work.  For more information, see496:ref:`callback-evaluation-order`.497498A callback is a function that is invoked with two parameters: the current499:class:`Context` and the value.  The context provides some useful features500such as quitting the application and gives access to other already501processed parameters.502503Here an example for a ``--version`` flag:504505.. click:example::506507    def print_version(ctx, param, value):508        if not value or ctx.resilient_parsing:509            return510        click.echo('Version 1.0')511        ctx.exit()512513    @click.command()514    @click.option('--version', is_flag=True, callback=print_version,515                  expose_value=False, is_eager=True)516    def hello():517        click.echo('Hello World!')518519The `expose_value` parameter prevents the pretty pointless ``version``520parameter from being passed to the callback.  If that was not specified, a521boolean would be passed to the `hello` script.  The `resilient_parsing`522flag is applied to the context if Click wants to parse the command line523without any destructive behavior that would change the execution flow.  In524this case, because we would exit the program, we instead do nothing.525526What it looks like:527528.. click:run::529530    invoke(hello)531    invoke(hello, args=['--version'])532533.. admonition:: Callback Signature Changes534535    In Click 2.0 the signature for callbacks changed.  For more536    information about these changes see :ref:`upgrade-to-2.0`.537538Yes Parameters539--------------540541For dangerous operations, it's very useful to be able to ask a user for542confirmation.  This can be done by adding a boolean ``--yes`` flag and543asking for confirmation if the user did not provide it and to fail in a544callback:545546.. click:example::547548    def abort_if_false(ctx, param, value):549        if not value:550            ctx.abort()551552    @click.command()553    @click.option('--yes', is_flag=True, callback=abort_if_false,554                  expose_value=False,555                  prompt='Are you sure you want to drop the db?')556    def dropdb():557        click.echo('Dropped all tables!')558559And what it looks like on the command line:560561.. click:run::562563    invoke(dropdb, input=['n'])564    invoke(dropdb, args=['--yes'])565566Because this combination of parameters is quite common, this can also be567replaced with the :func:`confirmation_option` decorator:568569.. click:example::570571    @click.command()572    @click.confirmation_option(prompt='Are you sure you want to drop the db?')573    def dropdb():574        click.echo('Dropped all tables!')575576.. admonition:: Callback Signature Changes577578    In Click 2.0 the signature for callbacks changed.  For more579    information about these changes see :ref:`upgrade-to-2.0`.580581Values from Environment Variables582---------------------------------583584A very useful feature of Click is the ability to accept parameters from585environment variables in addition to regular parameters.  This allows586tools to be automated much easier.  For instance, you might want to pass587a configuration file with a ``--config`` parameter but also support exporting588a ``TOOL_CONFIG=hello.cfg`` key-value pair for a nicer development589experience.590591This is supported by Click in two ways.  One is to automatically build592environment variables which is supported for options only.  To enable this593feature, the ``auto_envvar_prefix`` parameter needs to be passed to the594script that is invoked.  Each command and parameter is then added as an595uppercase underscore-separated variable.  If you have a subcommand596called ``run`` taking an option called ``reload`` and the prefix is597``WEB``, then the variable is ``WEB_RUN_RELOAD``.598599Example usage:600601.. click:example::602603    @click.command()604    @click.option('--username')605    def greet(username):606        click.echo('Hello %s!' % username)607608    if __name__ == '__main__':609        greet(auto_envvar_prefix='GREETER')610611And from the command line:612613.. click:run::614615    invoke(greet, env={'GREETER_USERNAME': 'john'},616           auto_envvar_prefix='GREETER')617618When using ``auto_envvar_prefix`` with command groups, the command name619needs to be included in the environment variable, between the prefix and620the parameter name, *i.e.* ``PREFIX_COMMAND_VARIABLE``. If you have a621subcommand called ``run-server`` taking an option called ``host`` and622the prefix is ``WEB``, then the variable is ``WEB_RUN_SERVER_HOST``.623624Example:625626.. click:example::627628   @click.group()629   @click.option('--debug/--no-debug')630   def cli(debug):631       click.echo('Debug mode is %s' % ('on' if debug else 'off'))632633   @cli.command()634   @click.option('--username')635   def greet(username):636       click.echo('Hello %s!' % username)637638   if __name__ == '__main__':639       cli(auto_envvar_prefix='GREETER')640641.. click:run::642643   invoke(cli, args=['greet',],644          env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},645          auto_envvar_prefix='GREETER')646647648The second option is to manually pull values in from specific environment649variables by defining the name of the environment variable on the option.650651Example usage:652653.. click:example::654655    @click.command()656    @click.option('--username', envvar='USERNAME')657    def greet(username):658        click.echo('Hello %s!' % username)659660    if __name__ == '__main__':661        greet()662663And from the command line:664665.. click:run::666667    invoke(greet, env={'USERNAME': 'john'})668669In that case it can also be a list of different environment variables670where the first one is picked.671672Multiple Values from Environment Values673---------------------------------------674675As options can accept multiple values, pulling in such values from676environment variables (which are strings) is a bit more complex.  The way677Click solves this is by leaving it up to the type to customize this678behavior.  For both ``multiple`` and ``nargs`` with values other than679``1``, Click will invoke the :meth:`ParamType.split_envvar_value` method to680perform the splitting.681682The default implementation for all types is to split on whitespace.  The683exceptions to this rule are the :class:`File` and :class:`Path` types684which both split according to the operating system's path splitting rules.685On Unix systems like Linux and OS X, the splitting happens for those on686every colon (``:``), and for Windows, on every semicolon (``;``).687688Example usage:689690.. click:example::691692    @click.command()693    @click.option('paths', '--path', envvar='PATHS', multiple=True,694                  type=click.Path())695    def perform(paths):696        for path in paths:697            click.echo(path)698699    if __name__ == '__main__':700        perform()701702And from the command line:703704.. click:run::705706    import os707    invoke(perform, env={'PATHS': './foo/bar%s./test' % os.path.pathsep})708709Other Prefix Characters710-----------------------711712Click can deal with alternative prefix characters other than ``-`` for713options.  This is for instance useful if you want to handle slashes as714parameters ``/`` or something similar.  Note that this is strongly715discouraged in general because Click wants developers to stay close to716POSIX semantics.  However in certain situations this can be useful:717718.. click:example::719720    @click.command()721    @click.option('+w/-w')722    def chmod(w):723        click.echo('writable=%s' % w)724725    if __name__ == '__main__':726        chmod()727728And from the command line:729730.. click:run::731732    invoke(chmod, args=['+w'])733    invoke(chmod, args=['-w'])734735Note that if you are using ``/`` as prefix character and you want to use a736boolean flag you need to separate it with ``;`` instead of ``/``:737738.. click:example::739740    @click.command()741    @click.option('/debug;/no-debug')742    def log(debug):743        click.echo('debug=%s' % debug)744745    if __name__ == '__main__':746        log()747748.. _ranges:749750Range Options751-------------752753A special mention should go to the :class:`IntRange` type, which works very754similarly to the :data:`INT` type, but restricts the value to fall into a755specific range (inclusive on both edges).  It has two modes:756757-   the default mode (non-clamping mode) where a value that falls outside758    of the range will cause an error.759-   an optional clamping mode where a value that falls outside of the760    range will be clamped.  This means that a range of ``0-5`` would761    return ``5`` for the value ``10`` or ``0`` for the value ``-1`` (for762    example).763764Example:765766.. click:example::767768    @click.command()769    @click.option('--count', type=click.IntRange(0, 20, clamp=True))770    @click.option('--digit', type=click.IntRange(0, 10))771    def repeat(count, digit):772        click.echo(str(digit) * count)773774    if __name__ == '__main__':775        repeat()776777And from the command line:778779.. click:run::780781    invoke(repeat, args=['--count=1000', '--digit=5'])782    invoke(repeat, args=['--count=1000', '--digit=12'])783784If you pass ``None`` for any of the edges, it means that the range is open785at that side.786787Callbacks for Validation788------------------------789790.. versionchanged:: 2.0791792If you want to apply custom validation logic, you can do this in the793parameter callbacks.  These callbacks can both modify values as well as794raise errors if the validation does not work.795796In Click 1.0, you can only raise the :exc:`UsageError` but starting with797Click 2.0, you can also raise the :exc:`BadParameter` error, which has the798added advantage that it will automatically format the error message to799also contain the parameter name.800801Example:802803.. click:example::804805    def validate_rolls(ctx, param, value):806        try:807            rolls, dice = map(int, value.split('d', 2))808            return (dice, rolls)809        except ValueError:810            raise click.BadParameter('rolls need to be in format NdM')811812    @click.command()813    @click.option('--rolls', callback=validate_rolls, default='1d6')814    def roll(rolls):815        click.echo('Rolling a %d-sided dice %d time(s)' % rolls)816817    if __name__ == '__main__':818        roll()819820And what it looks like:821822.. click:run::823824    invoke(roll, args=['--rolls=42'])825    println()826    invoke(roll, args=['--rolls=2d12'])