Skip to content
Myr

options.rst

This file

Path

docs/options.rst

695 lines · 19.0 KiB

Last changed by

Merge pull request #439 from tedmiston/masterArmin Ronacherbefore adoptionb465b72

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>`.1213Basic Value Options14-------------------1516The most basic option is a value option.  These options accept one17argument which is a value.  If no type is provided, the type of the default18value is used.  If no default value is provided, the type is assumed to be19:data:`STRING`.  By default, the name of the parameter is the first long20option defined; otherwise the first short one is used.2122.. click:example::2324    @click.command()25    @click.option('--n', default=1)26    def dots(n):27        click.echo('.' * n)2829And on the command line:3031.. click:run::3233   invoke(dots, args=['--n=2'])3435In this case the option is of type :data:`INT` because the default value36is an integer.3738Multi Value Options39-------------------4041Sometimes, you have options that take more than one argument.  For options,42only a fixed number of arguments is supported.  This can be configured by43the ``nargs`` parameter.  The values are then stored as a tuple.4445.. click:example::4647    @click.command()48    @click.option('--pos', nargs=2, type=float)49    def findme(pos):50        click.echo('%s / %s' % pos)5152And on the command line:5354.. click:run::5556    invoke(findme, args=['--pos', '2.0', '3.0'])5758.. _tuple-type:5960Tuples as Multi Value Options61-----------------------------6263.. versionadded:: 4.06465As you can see that by using `nargs` set to a specific number each item in66the resulting tuple is of the same type.  This might not be what you want.67Commonly you might want to use different types for different indexes in68the tuple.  For this you can directly specify a tuple as type:6970.. click:example::7172    @click.command()73    @click.option('--item', type=(unicode, int))74    def putitem(item):75        click.echo('name=%s id=%d' % item)7677And on the command line:7879.. click:run::8081    invoke(putitem, args=['--item', 'peter', '1338'])8283By using a tuple literal as type, `nargs` gets automatically set to the84length of the tuple and the :class:`click.Tuple` type is automatically85used.  The above example is thus equivalent to this:8687.. click:example::8889    @click.command()90    @click.option('--item', nargs=2, type=click.Tuple([unicode, int]))91    def putitem(item):92        click.echo('name=%s id=%d' % item)9394Multiple Options95----------------9697Similarly to ``nargs``, there is also the case of wanting to support a98parameter being provided multiple times to and have all values recorded --99not just the last one.  For instance, ``git commit -m foo -m bar`` would100record two lines for the commit message: ``foo`` and ``bar``. This can be101accomplished with the ``multiple`` flag:102103Example:104105.. click:example::106107    @click.command()108    @click.option('--message', '-m', multiple=True)109    def commit(message):110        click.echo('\n'.join(message))111112And on the command line:113114.. click:run::115116    invoke(commit, args=['-m', 'foo', '-m', 'bar'])117118Counting119--------120121In some very rare circumstances, it is interesting to use the repetition122of options to count an integer up.  This can be used for verbosity flags,123for instance:124125.. click:example::126127    @click.command()128    @click.option('-v', '--verbose', count=True)129    def log(verbose):130        click.echo('Verbosity: %s' % verbose)131132And on the command line:133134.. click:run::135136    invoke(log, args=['-vvv'])137138Boolean Flags139-------------140141Boolean flags are options that can be enabled or disabled.  This can be142accomplished by defining two flags in one go separated by a slash (``/``)143for enabling or disabling the option.  (If a slash is in an option string,144Click automatically knows that it's a boolean flag and will pass145``is_flag=True`` implicitly.)  Click always wants you to provide an enable146and disable flag so that you can change the default later.147148Example:149150.. click:example::151152    import sys153154    @click.command()155    @click.option('--shout/--no-shout', default=False)156    def info(shout):157        rv = sys.platform158        if shout:159            rv = rv.upper() + '!!!!111'160        click.echo(rv)161162And on the command line:163164.. click:run::165166    invoke(info, args=['--shout'])167    invoke(info, args=['--no-shout'])168169If you really don't want an off-switch, you can just define one and170manually inform Click that something is a flag:171172.. click:example::173174    import sys175176    @click.command()177    @click.option('--shout', is_flag=True)178    def info(shout):179        rv = sys.platform180        if shout:181            rv = rv.upper() + '!!!!111'182        click.echo(rv)183184And on the command line:185186.. click:run::187188    invoke(info, args=['--shout'])189190Note that if a slash is contained in your option already (for instance, if191you use Windows-style parameters where ``/`` is the prefix character), you192can alternatively split the parameters through ``;`` instead:193194.. click:example::195196    @click.command()197    @click.option('/debug;/no-debug')198    def log(debug):199        click.echo('debug=%s' % debug)200201    if __name__ == '__main__':202        log()203204.. versionchanged:: 6.0205206If you want to define an alias for the second option only, then you will207need to use leading whitespace to disambiguate the format string:208209Example:210211.. click:example::212213    import sys214215    @click.command()216    @click.option('--shout/--no-shout', ' /-S', default=False)217    def info(shout):218        rv = sys.platform219        if shout:220            rv = rv.upper() + '!!!!111'221        click.echo(rv)222223.. click:run::224225    invoke(info, args=['--help'])226227Feature Switches228----------------229230In addition to boolean flags, there are also feature switches.  These are231implemented by setting multiple options to the same parameter name and232defining a flag value.  Note that by providing the ``flag_value`` parameter,233Click will implicitly set ``is_flag=True``.234235To set a default flag, assign a value of `True` to the flag that should be236the default.237238.. click:example::239240    import sys241242    @click.command()243    @click.option('--upper', 'transformation', flag_value='upper',244                  default=True)245    @click.option('--lower', 'transformation', flag_value='lower')246    def info(transformation):247        click.echo(getattr(sys.platform, transformation)())248249And on the command line:250251.. click:run::252253    invoke(info, args=['--upper'])254    invoke(info, args=['--lower'])255    invoke(info)256257.. _choice-opts:258259Choice Options260--------------261262Sometimes, you want to have a parameter be a choice of a list of values.263In that case you can use :class:`Choice` type.  It can be instantiated264with a list of valid values.265266Example:267268.. click:example::269270    @click.command()271    @click.option('--hash-type', type=click.Choice(['md5', 'sha1']))272    def digest(hash_type):273        click.echo(hash_type)274275What it looks like:276277.. click:run::278279    invoke(digest, args=['--hash-type=md5'])280    println()281    invoke(digest, args=['--hash-type=foo'])282    println()283    invoke(digest, args=['--help'])284285.. _option-prompting:286287Prompting288---------289290In some cases, you want parameters that can be provided from the command line,291but if not provided, ask for user input instead.  This can be implemented with292Click by defining a prompt string.293294Example:295296.. click:example::297298    @click.command()299    @click.option('--name', prompt=True)300    def hello(name):301        click.echo('Hello %s!' % name)302303And what it looks like:304305.. click:run::306307    invoke(hello, args=['--name=John'])308    invoke(hello, input=['John'])309310If you are not happy with the default prompt string, you can ask for311a different one:312313.. click:example::314315    @click.command()316    @click.option('--name', prompt='Your name please')317    def hello(name):318        click.echo('Hello %s!' % name)319320What it looks like:321322.. click:run::323324    invoke(hello, input=['John'])325326Password Prompts327----------------328329Click also supports hidden prompts and asking for confirmation.  This is330useful for password input:331332.. click:example::333334    @click.command()335    @click.option('--password', prompt=True, hide_input=True,336                  confirmation_prompt=True)337    def encrypt(password):338        click.echo('Encrypting password to %s' % password.encode('rot13'))339340What it looks like:341342.. click:run::343344    invoke(encrypt, input=['secret', 'secret'])345346Because this combination of parameters is quite common, this can also be347replaced with the :func:`password_option` decorator:348349.. click:example::350351    @click.command()352    @click.password_option()353    def encrypt(password):354        click.echo('Encrypting password to %s' % password.encode('rot13'))355356Dynamic Defaults for Prompts357----------------------------358359The ``auto_envvar_prefix`` and ``default_map`` options for the context360allow the program to read option values from the environment or a361configuration file.  However, this overrides the prompting mechanism, so362that the user does not get the option to change the value interactively.363364If you want to let the user configure the default value, but still be365prompted if the option isn't specified on the command line, you can do so366by supplying a callable as the default value. For example, to get a default367from the environment:368369.. click:example::370371    @click.command()372    @click.option('--username', prompt=True,373                  default=lambda: os.environ.get('USER', ''))374    def hello(username):375        print("Hello,", username)376377Callbacks and Eager Options378---------------------------379380Sometimes, you want a parameter to completely change the execution flow.381For instance, this is the case when you want to have a ``--version``382parameter that prints out the version and then exits the application.383384Note: an actual implementation of a ``--version`` parameter that is385reusable is available in Click as :func:`click.version_option`.  The code386here is merely an example of how to implement such a flag.387388In such cases, you need two concepts: eager parameters and a callback.  An389eager parameter is a parameter that is handled before others, and a390callback is what executes after the parameter is handled.  The eagerness391is necessary so that an earlier required parameter does not produce an392error message.  For instance, if ``--version`` was not eager and a393parameter ``--foo`` was required and defined before, you would need to394specify it for ``--version`` to work.  For more information, see395:ref:`callback-evaluation-order`.396397A callback is a function that is invoked with two parameters: the current398:class:`Context` and the value.  The context provides some useful features399such as quitting the application and gives access to other already400processed parameters.401402Here an example for a ``--version`` flag:403404.. click:example::405406    def print_version(ctx, param, value):407        if not value or ctx.resilient_parsing:408            return409        click.echo('Version 1.0')410        ctx.exit()411412    @click.command()413    @click.option('--version', is_flag=True, callback=print_version,414                  expose_value=False, is_eager=True)415    def hello():416        click.echo('Hello World!')417418The `expose_value` parameter prevents the pretty pointless ``version``419parameter from being passed to the callback.  If that was not specified, a420boolean would be passed to the `hello` script.  The `resilient_parsing`421flag is applied to the context if Click wants to parse the command line422without any destructive behavior that would change the execution flow.  In423this case, because we would exit the program, we instead do nothing.424425What it looks like:426427.. click:run::428429    invoke(hello)430    invoke(hello, args=['--version'])431432.. admonition:: Callback Signature Changes433434    In Click 2.0 the signature for callbacks changed.  For more435    information about these changes see :ref:`upgrade-to-2.0`.436437Yes Parameters438--------------439440For dangerous operations, it's very useful to be able to ask a user for441confirmation.  This can be done by adding a boolean ``--yes`` flag and442asking for confirmation if the user did not provide it and to fail in a443callback:444445.. click:example::446447    def abort_if_false(ctx, param, value):448        if not value:449            ctx.abort()450451    @click.command()452    @click.option('--yes', is_flag=True, callback=abort_if_false,453                  expose_value=False,454                  prompt='Are you sure you want to drop the db?')455    def dropdb():456        click.echo('Dropped all tables!')457458And what it looks like on the command line:459460.. click:run::461462    invoke(dropdb, input=['n'])463    invoke(dropdb, args=['--yes'])464465Because this combination of parameters is quite common, this can also be466replaced with the :func:`confirmation_option` decorator:467468.. click:example::469470    @click.command()471    @click.confirmation_option(prompt='Are you sure you want to drop the db?')472    def dropdb():473        click.echo('Dropped all tables!')474475.. admonition:: Callback Signature Changes476477    In Click 2.0 the signature for callbacks changed.  For more478    information about these changes see :ref:`upgrade-to-2.0`.479480Values from Environment Variables481---------------------------------482483A very useful feature of Click is the ability to accept parameters from484environment variables in addition to regular parameters.  This allows485tools to be automated much easier.  For instance, you might want to pass486a configuration file with a ``--config`` parameter but also support exporting487a ``TOOL_CONFIG=hello.cfg`` key-value pair for a nicer development488experience.489490This is supported by Click in two ways.  One is to automatically build491environment variables which is supported for options only.  To enable this492feature, the ``auto_envvar_prefix`` parameter needs to be passed to the493script that is invoked.  Each command and parameter is then added as an494uppercase underscore-separated variable.  If you have a subcommand495called ``foo`` taking an option called ``bar`` and the prefix is496``MY_TOOL``, then the variable is ``MY_TOOL_FOO_BAR``.497498Example usage:499500.. click:example::501502    @click.command()503    @click.option('--username')504    def greet(username):505        click.echo('Hello %s!' % username)506507    if __name__ == '__main__':508        greet(auto_envvar_prefix='GREETER')509510And from the command line:511512.. click:run::513514    invoke(greet, env={'GREETER_USERNAME': 'john'},515           auto_envvar_prefix='GREETER')516517The second option is to manually pull values in from specific environment518variables by defining the name of the environment variable on the option.519520Example usage:521522.. click:example::523524    @click.command()525    @click.option('--username', envvar='USERNAME')526    def greet(username):527        click.echo('Hello %s!' % username)528529    if __name__ == '__main__':530        greet()531532And from the command line:533534.. click:run::535536    invoke(greet, env={'USERNAME': 'john'})537538In that case it can also be a list of different environment variables539where the first one is picked.540541Multiple Values from Environment Values542---------------------------------------543544As options can accept multiple values, pulling in such values from545environment variables (which are strings) is a bit more complex.  The way546Click solves this is by leaving it up to the type to customize this547behavior.  For both ``multiple`` and ``nargs`` with values other than548``1``, Click will invoke the :meth:`ParamType.split_envvar_value` method to549perform the splitting.550551The default implementation for all types is to split on whitespace.  The552exceptions to this rule are the :class:`File` and :class:`Path` types553which both split according to the operating system's path splitting rules.554On Unix systems like Linux and OS X, the splitting happens for those on555every colon (``:``), and for Windows, on every semicolon (``;``).556557Example usage:558559.. click:example::560561    @click.command()562    @click.option('paths', '--path', envvar='PATHS', multiple=True,563                  type=click.Path())564    def perform(paths):565        for path in paths:566            click.echo(path)567568    if __name__ == '__main__':569        perform()570571And from the command line:572573.. click:run::574575    import os576    invoke(perform, env={'PATHS': './foo/bar%s./test' % os.path.pathsep})577578Other Prefix Characters579-----------------------580581Click can deal with alternative prefix characters other than ``-`` for582options.  This is for instance useful if you want to handle slashes as583parameters ``/`` or something similar.  Note that this is strongly584discouraged in general because Click wants developers to stay close to585POSIX semantics.  However in certain situations this can be useful:586587.. click:example::588589    @click.command()590    @click.option('+w/-w')591    def chmod(w):592        click.echo('writable=%s' % w)593594    if __name__ == '__main__':595        chmod()596597And from the command line:598599.. click:run::600601    invoke(chmod, args=['+w'])602    invoke(chmod, args=['-w'])603604Note that if you are using ``/`` as prefix character and you want to use a605boolean flag you need to separate it with ``;`` instead of ``/``:606607.. click:example::608609    @click.command()610    @click.option('/debug;/no-debug')611    def log(debug):612        click.echo('debug=%s' % debug)613614    if __name__ == '__main__':615        log()616617.. _ranges:618619Range Options620-------------621622A special mention should go to the :class:`IntRange` type, which works very623similarly to the :data:`INT` type, but restricts the value to fall into a624specific range (inclusive on both edges).  It has two modes:625626-   the default mode (non-clamping mode) where a value that falls outside627    of the range will cause an error.628-   an optional clamping mode where a value that falls outside of the629    range will be clamped.  This means that a range of ``0-5`` would630    return ``5`` for the value ``10`` or ``0`` for the value ``-1`` (for631    example).632633Example:634635.. click:example::636637    @click.command()638    @click.option('--count', type=click.IntRange(0, 20, clamp=True))639    @click.option('--digit', type=click.IntRange(0, 10))640    def repeat(count, digit):641        click.echo(str(digit) * count)642643    if __name__ == '__main__':644        repeat()645646And from the command line:647648.. click:run::649650    invoke(repeat, args=['--count=1000', '--digit=5'])651    invoke(repeat, args=['--count=1000', '--digit=12'])652653If you pass ``None`` for any of the edges, it means that the range is open654at that side.655656Callbacks for Validation657------------------------658659.. versionchanged:: 2.0660661If you want to apply custom validation logic, you can do this in the662parameter callbacks.  These callbacks can both modify values as well as663raise errors if the validation does not work.664665In Click 1.0, you can only raise the :exc:`UsageError` but starting with666Click 2.0, you can also raise the :exc:`BadParameter` error, which has the667added advantage that it will automatically format the error message to668also contain the parameter name.669670Example:671672.. click:example::673674    def validate_rolls(ctx, param, value):675        try:676            rolls, dice = map(int, value.split('d', 2))677            return (dice, rolls)678        except ValueError:679            raise click.BadParameter('rolls need to be in format NdM')680681    @click.command()682    @click.option('--rolls', callback=validate_rolls, default='1d6')683    def roll(rolls):684        click.echo('Rolling a %d-sided dice %d time(s)' % rolls)685686    if __name__ == '__main__':687        roll()688689And what it looks like:690691.. click:run::692693    invoke(roll, args=['--rolls=42'])694    println()695    invoke(roll, args=['--rolls=2d12'])