Skip to content
Myr

options.rst

This file

Path

docs/options.rst

484 lines · 12.5 KiB

Last changed by

Always pick first optoin instead of longestArmin Ronacherbefore adoptionb8e766f

History of this file

Take it

1Options2=======34.. currentmodule:: click56Adding options to commands can be accomplished by the :func:`option`7decorator.  Since options can come in various different versions there8are a ton of parameters to configure their behavior.910Basic Value Options11-------------------1213The most basic option is a value option.  These options accept one14argument which is a value.  If no type is provided the type of the default15value is used.  If no default value is provided the type is assumed to be16:data:`STRING`.  The name of the parameter is by default the first long17option defined, otherwise the first short one.1819.. click:example::2021    @click.command()22    @click.option('--n', default=1)23    def dots(n):24        click.echo('.' * n)2526And on the command line:2728.. click:run::2930   invoke(dots, args=['--n=2'])3132In this case the option is of type :data:`INT` because the default value33is an integer.3435Multi Value Options36-------------------3738Sometimes you have options that take more than one argument.  For options39only a fixed number of arguments is supported.  This can be configured by40the ``nargs`` parameter.  The values are then stored as a tuple.4142.. click:example::4344    @click.command()45    @click.option('--pos', nargs=2, type=float)46    def findme(pos):47        click.echo('%s / %s' % pos)4849And on the command line:5051.. click:run::5253    invoke(findme, args=['--pos', '2.0', '3.0'])5455Multiple Options56----------------5758Similar to ``nargs`` there is also the case where sometimes you want to59support a parameter to be provided multiple times to and have all values60recorded and not just the last one.  For instance ``git commit -m foo -m61bar`` would record two lines for the commit message.  ``foo`` and ``bar``.62This can be accomplished with the ``multiple`` flag:6364Example:6566.. click:example::6768    @click.command()69    @click.option('--message', '-m', multiple=True)70    def commit(message):71        click.echo('\n'.join(message))7273And on the command line:7475.. click:run::7677    invoke(commit, args=['-m', 'foo', '-m', 'bar'])7879Counting80--------8182In some very rare circumstances it's interesting to use the repeating of83options to count an integer up.  This for instance can be used for84verbosity flags:8586.. click:example::8788    @click.command()89    @click.option('-v', '--verbose', count=True)90    def log(verbose):91        click.echo('Verbosity: %s' % verbose)9293And on the command line:9495.. click:run::9697    invoke(log, args=['-vvv'])9899Boolean Flags100-------------101102Boolean flags are options that can be enabled or disabled.  This can be103accomplished by defining two flags in one go separated by a slash (``/``)104for enabling or disabling the option.  Click always wants you to provide105an enable and disable flag so that you can change the default later.106107Example:108109.. click:example::110111    import os112113    @click.command()114    @click.option('--shout/--no-shout', default=False)115    def info(shout):116        rv = os.uname()[0]117        if shout:118            rv = rv.upper() + '!!!!111'119        click.echo(rv)120121And on the command line:122123.. click:run::124125    invoke(info, args=['--shout'])126    invoke(info, args=['--no-shout'])127128If you really don't want an off-switch you can just define one and129manually inform click that something is a flag:130131.. click:example::132133    import os134135    @click.command()136    @click.option('--shout', is_flag=True)137    def info(shout):138        rv = os.uname()[0]139        if shout:140            rv = rv.upper() + '!!!!111'141        click.echo(rv)142143And on the command line:144145.. click:run::146147    invoke(info, args=['--shout'])148149Feature Switches150----------------151152In addition to boolean flags there are also feature switches.  These are153implemented by setting multiple options to the same parameter name and by154defining a flag value.  To set a default flag assign a value of `True` to155the flag that should be the default.156157.. click:example::158159    import os160161    @click.command()162    @click.option('--upper', 'transformation', flag_value='upper',163                  default=True)164    @click.option('--lower', 'transformation', flag_value='lower')165    def info(transformation):166        click.echo(getattr(os.uname()[0], transformation)())167168And on the command line:169170.. click:run::171172    invoke(info, args=['--upper'])173    invoke(info, args=['--lower'])174    invoke(info)175176.. _choice-opts:177178Choice Options179--------------180181Sometimes you want to have a parameter be a choice of a list of values.182In that case you can use :class:`Choice` type.  It can be instantiated183with a list of valid values.184185Example:186187.. click:example::188189    @click.command()190    @click.option('--hash-type', type=click.Choice(['md5', 'sha1']))191    def digest(hash_type):192        click.echo(hash_type)193194What it looks like:195196.. click:run::197198    invoke(digest, args=['--hash-type=md5'])199    println()200    invoke(digest, args=['--hash-type=foo'])201    println()202    invoke(digest, args=['--help'])203204.. _option-prompting:205206Prompting207---------208209Sometimes you want parameters that can either be provided from the command210line or if not, you want to ask for user input.  This can be implemented211with click by defining a prompt string.212213Example:214215.. click:example::216217    @click.command()218    @click.option('--name', prompt=True)219    def hello(name):220        click.echo('Hello %s!' % name)221222And what it looks like:223224.. click:run::225226    invoke(hello, args=['--name=John'])227    invoke(hello, input=['John'])228229If you are not happy with the default prompt string you can ask for230a different one:231232.. click:example::233234    @click.command()235    @click.option('--name', prompt='Your name please')236    def hello(name):237        click.echo('Hello %s!' % name)238239What it looks like:240241.. click:run::242243    invoke(hello, input=['John'])244245Password Prompts246----------------247248Click also supports hidden prompts and asking for confirmation.  This is249useful for password input:250251.. click:example::252253    @click.command()254    @click.option('--password', prompt=True, hide_input=True,255                  confirmation_prompt=True)256    def encrypt(password):257        click.echo('Encrypting password to %s' % password.encode('rot13'))258259What it looks like:260261.. click:run::262263    invoke(encrypt, input=['secret', 'secret'])264265Because this combination of parameters is quite common this can also be266replaced with the :func:`password_option` decorator:267268.. click:example::269270    @click.command()271    @click.password_option()272    def encrypt(password):273        click.echo('Encrypting password to %s' % password.encode('rot13'))274275Callbacks and Eager Options276---------------------------277278Sometimes you want a parameter to completely change the execution flow.279This for instance is the case when you want to have a ``--version``280parameter that prints out the version and then exits the application.281282In such cases you need two concepts: eager parameters and a callback.  An283eager parameter is a parameter that is handled before others and a284callback is what executes after the parameter is handled.  The eagerness285is necessary so that an earlier required parameter does not produce an286error message.  For instance if ``--version`` was not eager and a287parameter ``--foo`` was required and defined before, you would need to288specify it for ``--version`` to work.289290A callback is a function that is invoked with two parameters: the current291:class:`Context` and the value.  The context provides some useful features292such as quitting the application and gives access to other already293processed parameters.294295Here an example for a ``--version`` flag:296297.. click:example::298299    def print_version(ctx, value):300        if not value:301            return302        click.echo('Version 1.0')303        ctx.exit()304305    @click.command()306    @click.option('--version', is_flag=True, callback=print_version,307                  expose_value=False, is_eager=True)308    def hello():309        click.echo('Hello World!')310311The `expose_value` parameter prevents the now pretty pointless ``version``312parameter to be passed to the callback.  If that was not specified a313boolean would be passed to the `hello` script.314315What it looks like:316317.. click:run::318319    invoke(hello)320    invoke(hello, args=['--version'])321322Yes Parameters323--------------324325For dangerous operations it's very useful to be able to ask a user for326confirmation.  This can be done by adding a boolean ``--yes`` flag and327asking for confirmation if the user did not provide it and to fail in a328callback:329330.. click:example::331332    def abort_if_false(ctx, value):333        if not value:334            ctx.abort()335336    @click.command()337    @click.option('--yes', is_flag=True, callback=abort_if_false,338                  expose_value=False,339                  prompt='Are you sure you want to drop the db?')340    def dropdb():341        click.echo('Dropped all tables!')342343And what it looks like on the command line:344345.. click:run::346347    invoke(dropdb, input=['n'])348    invoke(dropdb, args=['--yes'])349350Because this combination of parameters is quite common this can also be351replaced with the :func:`confirmation_option` decorator:352353.. click:example::354355    @click.command()356    @click.confirmation_option('Are you sure you want to drop the db?')357    def dropdb():358        click.echo('Dropped all tables!')359360Values from Environment Variables361---------------------------------362363A very useful feature of click is the ability to accept parameters from364environment variables in addition to regular parameters.  This allows365tools to be automated much easier.  For instance you might want to pass366the config file as ``--config`` parameter but also support exporting a367``TOOL_CONFIG=hello.cfg`` key / value pair for a nicer development368experience.369370This is supported by click in two ways.  One is to automatically build371environment variables which is supported for options only.  To enable this372feature the ``auto_envvar_prefix`` parameter needs to be passed to the373script that is invoked.  Each command and parameter is then added as374underscore-separated variable in uppercase.  So if you have a subcommand375called ``foo`` taking an option called ``bar`` and the prefix is376``MY_TOOL`` then the variable is ``MY_TOOL_FOO_BAR``.377378Example usage:379380.. click:example::381382    @click.command()383    @click.option('--username')384    def greet(username):385        click.echo('Hello %s!' % username)386387    if __name__ == '__main__':388        greet(auto_envvar_prefix='GREETER')389390And from the command line:391392.. click:run::393394    invoke(greet, env={'GREETER_USERNAME': 'john'},395           auto_envvar_prefix='GREETER')396397The second option is to manually pull values in from specific environment398variables by defining the name of the environment variable on the option.399400Example usage:401402.. click:example::403404    @click.command()405    @click.option('--username', envvar='USERNAME')406    def greet(username):407        click.echo('Hello %s!' % username)408409    if __name__ == '__main__':410        greet()411412And from the command line:413414.. click:run::415416    invoke(greet, env={'USERNAME': 'john'})417418In that case it can also be a list of different environment variables419where the first one is picked.420421Other Prefix Characters422-----------------------423424Click can deal with alternative prefix characters, other than ``-`` for425options.  This is for instance useful if you want to handle slashes as426parameters ``/`` or something similar.  Note that this is strongly427discouraged in general because click wants developers to stay close to428POSIX semantics.  However in certain situations this can be useful:429430.. click:example::431432    @click.command()433    @click.option('+w/-w')434    def chmod(w):435        click.echo('writable=%s' % w)436437    if __name__ == '__main__':438        chmod()439440And from the command line:441442.. click:run::443444    invoke(chmod, args=['+w'])445    invoke(chmod, args=['-w'])446447.. _ranges:448449Range Options450-------------451452A special mention should go to the :class:`IntRange` type which works very453similar to the :data:`INT` type but restricts the value to fall into a454specific range (inclusive on both edges).  It has two modes:455456-   the default mode (non clamping mode) where a value that falls outside457    of the range will cause an error.458-   an optional clamping mode where a value that falls outside of the459    range will be clamped.  This means that a range of ``0-5`` would460    return ``5`` for the value ``10`` or ``0`` for the value ``-1`` (for461    example).462463Example:464465.. click:example::466467    @click.command()468    @click.option('--count', type=click.IntRange(0, 20, clamp=True))469    @click.option('--digit', type=click.IntRange(0, 10))470    def repeat(count, digit):471        click.echo(str(digit) * count)472473    if __name__ == '__main__':474        repeat()475476And from the command line:477478.. click:run::479480    invoke(repeat, args=['--count=1000', '--digit=5'])481    invoke(repeat, args=['--count=1000', '--digit=12'])482483If you pass ``None`` for any of the edges it means that the range is open484at that side.