Skip to content
Myr

options.rst

This file

Path

docs/options.rst

608 lines · 16.5 KiB

Last changed by

Merge pull request #113 from iKevinY/doc-fixesArmin Ronacherbefore adoptione0ea94a

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`.  By default, the name of the parameter is the first long17option defined; otherwise the first short one is used.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 options,39only 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----------------5758Similarly to ``nargs``, there is also the case of wanting to support a59parameter being provided multiple times to and have all values recorded --60not just the last one.  For instance, ``git commit -m foo -m bar`` would61record two lines for the commit message: ``foo`` and ``bar``. This can be62accomplished 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 is interesting to use the repetition83of options to count an integer up.  This can be used for verbosity flags,84for instance: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.  (If a slash is in an option string,105click automatically knows that it's a boolean flag and will pass106``is_flag=True`` implicitly.)  Click always wants you to provide an enable107and disable flag so that you can change the default later.108109Example:110111.. click:example::112113    import os114115    @click.command()116    @click.option('--shout/--no-shout', default=False)117    def info(shout):118        rv = os.uname()[0]119        if shout:120            rv = rv.upper() + '!!!!111'121        click.echo(rv)122123And on the command line:124125.. click:run::126127    invoke(info, args=['--shout'])128    invoke(info, args=['--no-shout'])129130If you really don't want an off-switch, you can just define one and131manually inform click that something is a flag:132133.. click:example::134135    import os136137    @click.command()138    @click.option('--shout', is_flag=True)139    def info(shout):140        rv = os.uname()[0]141        if shout:142            rv = rv.upper() + '!!!!111'143        click.echo(rv)144145And on the command line:146147.. click:run::148149    invoke(info, args=['--shout'])150151Note that if a slash is contained in your option already (for instance, if152you use Windows-style parameters where ``/`` is the prefix character), you153can alternatively split the parameters through ``;`` instead:154155.. click:example::156157    @click.command()158    @click.option('/debug;/no-debug')159    def log(debug):160        click.echo('debug=%s' % debug)161162    if __name__ == '__main__':163        log()164165Feature Switches166----------------167168In addition to boolean flags, there are also feature switches.  These are169implemented by setting multiple options to the same parameter name and170defining a flag value.  Note that by providing the ``flag_value`` parameter,171click will implicitly set ``is_flag=True``.172173To set a default flag, assign a value of `True` to the flag that should be174the default.175176.. click:example::177178    import os179180    @click.command()181    @click.option('--upper', 'transformation', flag_value='upper',182                  default=True)183    @click.option('--lower', 'transformation', flag_value='lower')184    def info(transformation):185        click.echo(getattr(os.uname()[0], transformation)())186187And on the command line:188189.. click:run::190191    invoke(info, args=['--upper'])192    invoke(info, args=['--lower'])193    invoke(info)194195.. _choice-opts:196197Choice Options198--------------199200Sometimes, you want to have a parameter be a choice of a list of values.201In that case you can use :class:`Choice` type.  It can be instantiated202with a list of valid values.203204Example:205206.. click:example::207208    @click.command()209    @click.option('--hash-type', type=click.Choice(['md5', 'sha1']))210    def digest(hash_type):211        click.echo(hash_type)212213What it looks like:214215.. click:run::216217    invoke(digest, args=['--hash-type=md5'])218    println()219    invoke(digest, args=['--hash-type=foo'])220    println()221    invoke(digest, args=['--help'])222223.. _option-prompting:224225Prompting226---------227228In some cases, you want parameters that can be provided from the command line,229but if not provided, ask for user input instead.  This can be implemented with230click by defining a prompt string.231232Example:233234.. click:example::235236    @click.command()237    @click.option('--name', prompt=True)238    def hello(name):239        click.echo('Hello %s!' % name)240241And what it looks like:242243.. click:run::244245    invoke(hello, args=['--name=John'])246    invoke(hello, input=['John'])247248If you are not happy with the default prompt string, you can ask for249a different one:250251.. click:example::252253    @click.command()254    @click.option('--name', prompt='Your name please')255    def hello(name):256        click.echo('Hello %s!' % name)257258What it looks like:259260.. click:run::261262    invoke(hello, input=['John'])263264Password Prompts265----------------266267Click also supports hidden prompts and asking for confirmation.  This is268useful for password input:269270.. click:example::271272    @click.command()273    @click.option('--password', prompt=True, hide_input=True,274                  confirmation_prompt=True)275    def encrypt(password):276        click.echo('Encrypting password to %s' % password.encode('rot13'))277278What it looks like:279280.. click:run::281282    invoke(encrypt, input=['secret', 'secret'])283284Because this combination of parameters is quite common, this can also be285replaced with the :func:`password_option` decorator:286287.. click:example::288289    @click.command()290    @click.password_option()291    def encrypt(password):292        click.echo('Encrypting password to %s' % password.encode('rot13'))293294Callbacks and Eager Options295---------------------------296297Sometimes, you want a parameter to completely change the execution flow.298For instance, this is the case when you want to have a ``--version``299parameter that prints out the version and then exits the application.300301In such cases, you need two concepts: eager parameters and a callback.  An302eager parameter is a parameter that is handled before others, and a303callback is what executes after the parameter is handled.  The eagerness304is necessary so that an earlier required parameter does not produce an305error message.  For instance, if ``--version`` was not eager and a306parameter ``--foo`` was required and defined before, you would need to307specify it for ``--version`` to work.  For more information, see308:ref:`callback-evaluation-order`.309310A callback is a function that is invoked with two parameters: the current311:class:`Context` and the value.  The context provides some useful features312such as quitting the application and gives access to other already313processed parameters.314315Here an example for a ``--version`` flag:316317.. click:example::318319    def print_version(ctx, param, value):320        if not value or ctx.resilient_parsing:321            return322        click.echo('Version 1.0')323        ctx.exit()324325    @click.command()326    @click.option('--version', is_flag=True, callback=print_version,327                  expose_value=False, is_eager=True)328    def hello():329        click.echo('Hello World!')330331The `expose_value` parameter prevents the pretty pointless ``version``332parameter from being passed to the callback.  If that was not specified, a333boolean would be passed to the `hello` script.  The `resilient_parsing`334flag is applied to the context if click wants to parse the command line335without and destructive behavior that would change the execution flow.  In336this case, because we would exit the program, we instead do nothing.337338What it looks like:339340.. click:run::341342    invoke(hello)343    invoke(hello, args=['--version'])344345.. admonition:: Callback Signature Changes346347    In click 2.0 the signature for callbacks changed.  For more348    information about these changes see :ref:`upgrade-to-2.0`.349350Yes Parameters351--------------352353For dangerous operations, it's very useful to be able to ask a user for354confirmation.  This can be done by adding a boolean ``--yes`` flag and355asking for confirmation if the user did not provide it and to fail in a356callback:357358.. click:example::359360    def abort_if_false(ctx, param, value):361        if not value:362            ctx.abort()363364    @click.command()365    @click.option('--yes', is_flag=True, callback=abort_if_false,366                  expose_value=False,367                  prompt='Are you sure you want to drop the db?')368    def dropdb():369        click.echo('Dropped all tables!')370371And what it looks like on the command line:372373.. click:run::374375    invoke(dropdb, input=['n'])376    invoke(dropdb, args=['--yes'])377378Because this combination of parameters is quite common, this can also be379replaced with the :func:`confirmation_option` decorator:380381.. click:example::382383    @click.command()384    @click.confirmation_option(help='Are you sure you want to drop the db?')385    def dropdb():386        click.echo('Dropped all tables!')387388.. admonition:: Callback Signature Changes389390    In click 2.0 the signature for callbacks changed.  For more391    information about these changes see :ref:`upgrade-to-2.0`.392393Values from Environment Variables394---------------------------------395396A very useful feature of click is the ability to accept parameters from397environment variables in addition to regular parameters.  This allows398tools to be automated much easier.  For instance, you might want to pass399a configuration file with a ``--config`` parameter but also support exporting400a ``TOOL_CONFIG=hello.cfg`` key-value pair for a nicer development401experience.402403This is supported by click in two ways.  One is to automatically build404environment variables which is supported for options only.  To enable this405feature, the ``auto_envvar_prefix`` parameter needs to be passed to the406script that is invoked.  Each command and parameter is then added as an407uppercase underscore-separated variable.  If you have a subcommand408called ``foo`` taking an option called ``bar`` and the prefix is409``MY_TOOL``, then the variable is ``MY_TOOL_FOO_BAR``.410411Example usage:412413.. click:example::414415    @click.command()416    @click.option('--username')417    def greet(username):418        click.echo('Hello %s!' % username)419420    if __name__ == '__main__':421        greet(auto_envvar_prefix='GREETER')422423And from the command line:424425.. click:run::426427    invoke(greet, env={'GREETER_USERNAME': 'john'},428           auto_envvar_prefix='GREETER')429430The second option is to manually pull values in from specific environment431variables by defining the name of the environment variable on the option.432433Example usage:434435.. click:example::436437    @click.command()438    @click.option('--username', envvar='USERNAME')439    def greet(username):440        click.echo('Hello %s!' % username)441442    if __name__ == '__main__':443        greet()444445And from the command line:446447.. click:run::448449    invoke(greet, env={'USERNAME': 'john'})450451In that case it can also be a list of different environment variables452where the first one is picked.453454Multiple Values from Environment Values455---------------------------------------456457As options can accept multiple values, pulling in such values from458environment variables (which are strings) is a bit more complex.  The way459click solves this is by leaving it up to the type to customize this460behavior.  For both ``multiple`` and ``nargs`` with values other than461``1``, click will invoke the :meth:`ParamType.split_envvar_value` method to462perform the splitting.463464The default implementation for all types is to split on whitespace.  The465exceptions to this rule are the :class:`File` and :class:`Path` types466which both split according to the operating system's path splitting rules.467On Unix systems like Linux and OS X, the splitting happens for those on468every colon (``:``), and for Windows, on every semicolon (``;``).469470Example usage:471472.. click:example::473474    @click.command()475    @click.option('paths', '--path', envvar='PATHS', multiple=True,476                  type=click.Path())477    def perform(paths):478        for path in paths:479            click.echo(path)480481    if __name__ == '__main__':482        perform()483484And from the command line:485486.. click:run::487488    import os489    invoke(perform, env={'PATHS': './foo/bar%s./test' % os.path.pathsep})490491Other Prefix Characters492-----------------------493494Click can deal with alternative prefix characters other than ``-`` for495options.  This is for instance useful if you want to handle slashes as496parameters ``/`` or something similar.  Note that this is strongly497discouraged in general because click wants developers to stay close to498POSIX semantics.  However in certain situations this can be useful:499500.. click:example::501502    @click.command()503    @click.option('+w/-w')504    def chmod(w):505        click.echo('writable=%s' % w)506507    if __name__ == '__main__':508        chmod()509510And from the command line:511512.. click:run::513514    invoke(chmod, args=['+w'])515    invoke(chmod, args=['-w'])516517Note that if you are using ``/`` as prefix character and you want to use a518boolean flag you need to separate it with ``;`` instead of ``/``:519520.. click:example::521522    @click.command()523    @click.option('/debug;/no-debug')524    def log(debug):525        click.echo('debug=%s' % debug)526527    if __name__ == '__main__':528        log()529530.. _ranges:531532Range Options533-------------534535A special mention should go to the :class:`IntRange` type, which works very536similarly to the :data:`INT` type, but restricts the value to fall into a537specific range (inclusive on both edges).  It has two modes:538539-   the default mode (non-clamping mode) where a value that falls outside540    of the range will cause an error.541-   an optional clamping mode where a value that falls outside of the542    range will be clamped.  This means that a range of ``0-5`` would543    return ``5`` for the value ``10`` or ``0`` for the value ``-1`` (for544    example).545546Example:547548.. click:example::549550    @click.command()551    @click.option('--count', type=click.IntRange(0, 20, clamp=True))552    @click.option('--digit', type=click.IntRange(0, 10))553    def repeat(count, digit):554        click.echo(str(digit) * count)555556    if __name__ == '__main__':557        repeat()558559And from the command line:560561.. click:run::562563    invoke(repeat, args=['--count=1000', '--digit=5'])564    invoke(repeat, args=['--count=1000', '--digit=12'])565566If you pass ``None`` for any of the edges, it means that the range is open567at that side.568569Callbacks for Validation570------------------------571572.. versionchanged:: 2.0573574If you want to apply custom validation logic, you can do this in the575parameter callbacks.  These callbacks can both modify values as well as576raise errors if the validation does not work.577578In click 1.0, you can only raise the :exc:`UsageError` but starting with579click 2.0, you can also raise the :exc:`BadParameter` error, which has the580added advantage that it will automatically format the error message to581also contain the parameter name.582583Example:584585.. click:example::586587    def validate_rolls(ctx, param, value):588        try:589            rolls, dice = map(int, value.split('d', 2))590            return (dice, rolls)591        except ValueError:592            raise click.BadParameter('rolls need to be in format NdM')593594    @click.command()595    @click.option('--rolls', callback=validate_rolls, default='1d6')596    def roll(rolls):597        click.echo('Rolling a %d-sided dice %d time(s)' % rolls)598599    if __name__ == '__main__':600        roll()601602And what it looks like:603604.. click:run::605606    invoke(roll, args=['--rolls=42'])607    println()608    invoke(roll, args=['--rolls=2d12'])