Skip to content
Myr

options.rst

This file

Path

docs/options.rst

420 lines · 10.8 KiB

Last changed by

Make documentation invoke click and fix a bunch of issuesArmin Ronacherbefore adoption0a44670

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 the longest option defined.1718.. click:example::1920    @click.command()21    @click.option('--n', default=1)22    def dots(n):23        print('.' * n)2425And on the command line:2627.. click:run::2829   invoke(dots, args=['--n=2'])3031In this case the option is of type :data:`INT` because the default value32is an integer.3334Multi Value Options35-------------------3637Sometimes you have options that take more than one argument.  For options38only a fixed number of arguments is supported.  This can be configured by39the ``nargs`` parameter.  The values are then stored as a tuple.4041.. click:example::4243    @click.command()44    @click.option('--pos', nargs=2, type=float)45    def findme(pos):46        print('%s / %s' % pos)4748And on the command line:4950.. click:run::5152    invoke(findme, args=['--pos', '2.0', '3.0'])5354Multiple Options55----------------5657Similar to ``nargs`` there is also the case where sometimes you want to58support a parameter to be provided multiple times to and have all values59recorded and not just the last one.  For instance ``git commit -m foo -m60bar`` would record two lines for the commit message.  ``foo`` and ``bar``.61This can be accomplished with the ``multiple`` flag:6263Example:6465.. click:example::6667    @click.command()68    @click.option('--message', '-m', multiple=True)69    def commit(message):70        print('\n'.join(message))7172And on the command line:7374.. click:run::7576    invoke(commit, args=['-m', 'foo', '-m', 'bar'])7778Counting79--------8081If you have used ``optparse`` or ``argparse`` before you might be missing82support for counting.  This is a very rarely useful feature, usually only83useful for implementing verbosity flags.  It can however be emulated by84using the multiple flag and taking the length of the end result:8586.. click:example::8788    @click.command()89    @click.option('-v', '--verbose', is_flag=True, multiple=True)90    def log(verbose):91        verbosity = len(verbose)92        print('Verbosity: %s' % verbosity)9394And on the command line:9596.. click:run::9798    invoke(log, args=['-vvv'])99100Boolean Flags101-------------102103Boolean flags are options that can be enabled or disabled.  This can be104accomplished by defining two flags in one go separated by a slash (``/``)105for enabling or disabling the option.  Click always wants you to provide106an enable and disable flag so that you can change the default later.107108Example:109110.. click:example::111112    import os113114    @click.command()115    @click.option('--shout/--no-shout', default=False)116    def info(shout):117        rv = os.uname()[0]118        if shout:119            rv = rv.upper() + '!!!!111'120        print(rv)121122And on the command line:123124.. click:run::125126    invoke(info, args=['--shout'])127    invoke(info, args=['--no-shout'])128129If you really don't want an off-switch you can just define one and130manually inform click that something is a flag:131132.. click:example::133134    import os135136    @click.command()137    @click.option('--shout', is_flag=True)138    def info(shout):139        rv = os.uname()[0]140        if shout:141            rv = rv.upper() + '!!!!111'142        print(rv)143144And on the command line:145146.. click:run::147148    invoke(info, args=['--shout'])149150Feature Switches151----------------152153In addition to boolean flags there are also feature switches.  These are154implemented by setting multiple options to the same parameter name and by155defining a flag value.  To set a default flag assign a value of `True` to156the flag that should be the default.157158.. click:example::159160    import os161162    @click.command()163    @click.option('--upper', 'transformation', flag_value='upper',164                  default=True)165    @click.option('--lower', 'transformation', flag_value='lower')166    def info(transformation):167        print(getattr(os.uname()[0], transformation)())168169And on the command line:170171.. click:run::172173    invoke(info, args=['--upper'])174    invoke(info, args=['--lower'])175    invoke(info)176177.. _choice-opts:178179Choice Options180--------------181182Sometimes you want to have a parameter be a choice of a list of values.183In that case you can use :class:`Choice` type.  It can be instanciated184with a list of valid values.185186Example:187188.. click:example::189190    @click.command()191    @click.option('--hash-type', type=click.Choice(['md5', 'sha1']))192    def digest(hash_type):193        print(hash_type)194195What it looks like:196197.. click:run::198199    invoke(digest, args=['--hash-type=md5'])200    println()201    invoke(digest, args=['--hash-type=foo'])202    println()203    invoke(digest, args=['--help'])204205.. _option-prompting:206207Prompting208---------209210Sometimes you want parameters that can either be provided from the command211line or if not, you want to ask for user input.  This can be implemented212with click by defining a prompt string.213214Example:215216.. click:example::217218    @click.command()219    @click.option('--name', prompt=True)220    def hello(name):221        print('Hello %s!' % name)222223And what it looks like:224225.. click:run::226227    invoke(hello, args=['--name=John'])228    invoke(hello, input=['John'])229230If you are not happy with the default prompt string you can ask for231a different one:232233.. click:example::234235    @click.command()236    @click.option('--name', prompt='Your name please')237    def hello(name):238        print('Hello %s!' % name)239240What it looks like:241242.. click:run::243244    invoke(hello, input=['John'])245246Password Prompts247----------------248249Click also supports hidden prompts and asking for confirmation.  This is250useful for password input:251252.. click:example::253254    @click.command()255    @click.option('--password', prompt=True, hide_input=True,256                  confirmation_prompt=True)257    def encrypt(password):258        print('Encrypting password to %s' % password.encode('rot13'))259260What it looks like:261262.. click:run::263264    invoke(encrypt, input=['secret', 'secret'])265266Because this combination of parameters is quite common this can also be267replaced with the :func:`password_option` decorator:268269.. click:example::270271    @click.command()272    @click.password_option()273    def encrypt(password):274        print('Encrypting password to %s' % password.encode('rot13'))275276Callbacks and Eager Options277---------------------------278279Sometimes you want a parameter to completely change the execution flow.280This for instance is the case when you want to have a ``--version``281parameter that prints out the version and then exits the application.282283In such cases you need two concepts: eager parameters and a callback.  An284eager parameter is a parameter that is handled before others and a285callback is what executes after the parameter is handled.  The eagerness286is necessary so that an earlier required parameter does not produce an287error message.  For instance if ``--version`` was not eager and a288parameter ``--foo`` was required and defined before, you would need to289specify it for ``--version`` to work.290291A callback is a function that is invoked with two parameters: the current292:class:`Context` and the value.  The context provides some useful features293such as quitting the application and gives access to other already294processed parameters.295296Here an example for a ``--version`` flag:297298.. click:example::299300    def print_version(ctx, value):301        if not value:302            return303        print('Version 1.0')304        ctx.exit()305306    @click.command()307    @click.option('--version', is_flag=True, callback=print_version,308                  expose_value=False, is_eager=True)309    def hello():310        print('Hello World!')311312The `expose_value` parameter prevents the now pretty pointless ``version``313parameter to be passed to the callback.  If that was not specified a314boolean would be passed to the `hello` script.315316What it looks like:317318.. click:run::319320    invoke(hello)321    invoke(hello, args=['--version'])322323Yes Parameters324--------------325326For dangerous operations it's very useful to be able to ask a user for327confirmation.  This can be done by adding a boolean ``--yes`` flag and328asking for confirmation if the user did not provide it and to fail in a329callback:330331.. click:example::332333    def abort_if_false(ctx, value):334        if not value:335            ctx.abort()336337    @click.command()338    @click.option('--yes', is_flag=True, callback=abort_if_false,339                  expose_value=False,340                  prompt='Are you sure you want to drop the db?')341    def dropdb():342        print('Dropped all tables!')343344And what it looks like on the command line:345346.. click:run::347348    invoke(dropdb, input=['n'])349    invoke(dropdb, args=['--yes'])350351Because this combination of parameters is quite common this can also be352replaced with the :func:`confirmation_option` decorator:353354.. click:example::355356    @click.command()357    @click.confirmation_option('Are you sure you want to drop the db?')358    def dropdb():359        print('Dropped all tables!')360361Values from Environment Variables362---------------------------------363364A very useful feature of click is the ability to accept parameters from365environment variables in addition to regular parameters.  This allows366tools to be automated much easier.  For instance you might want to pass367the config file as ``--config`` parameter but also support exporting a368``TOOL_CONFIG=hello.cfg`` key / value pair for a nicer development369experience.370371This is supported by click in two ways.  One is to automatically build372environment variables which is supported for options only.  To enable this373feature the ``auto_envvar_prefix`` parameter needs to be passed to the374script that is invoked.  Each command and parameter is then added as375underscore-separated variable in uppercase.  So if you have a subcommand376called ``foo`` taking an option called ``bar`` and the prefix is377``MY_TOOL`` then the variable is ``MY_TOOL_FOO_BAR``.378379Example usage:380381.. click:example::382383    @click.command()384    @click.option('--username')385    def greet(username):386        print('Hello %s!' % username)387388    if __name__ == '__main__':389        greet(auto_envvar_prefix='GREETER')390391And from the command line:392393.. click:run::394395    invoke(greet, env={'GREETER_USERNAME': 'john'},396           auto_envvar_prefix='GREETER')397398The second option is to manually pull values in from specific environment399variables by defining the name of the environment variable on the option.400401Example usage:402403.. click:example::404405    @click.command()406    @click.option('--username', envvar='USERNAME')407    def greet(username):408        print('Hello %s!' % username)409410    if __name__ == '__main__':411        greet()412413And from the command line:414415.. click:run::416417    invoke(greet, env={'USERNAME': 'john'})418419In that case it can also be a list of different environment variables420where the first one is picked.