options.rst
This file
Path
docs/options.rst
672 lines · 18.5 KiB
Last changed by
Merge pull request #325 from pfmoore/dynamic_default_docMarkus Unterwaditzerbefore adoptionaa9a713
History of this fileTake 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()203204Feature Switches205----------------206207In addition to boolean flags, there are also feature switches. These are208implemented by setting multiple options to the same parameter name and209defining a flag value. Note that by providing the ``flag_value`` parameter,210Click will implicitly set ``is_flag=True``.211212To set a default flag, assign a value of `True` to the flag that should be213the default.214215.. click:example::216217 import sys218219 @click.command()220 @click.option('--upper', 'transformation', flag_value='upper',221 default=True)222 @click.option('--lower', 'transformation', flag_value='lower')223 def info(transformation):224 click.echo(getattr(sys.platform, transformation)())225226And on the command line:227228.. click:run::229230 invoke(info, args=['--upper'])231 invoke(info, args=['--lower'])232 invoke(info)233234.. _choice-opts:235236Choice Options237--------------238239Sometimes, you want to have a parameter be a choice of a list of values.240In that case you can use :class:`Choice` type. It can be instantiated241with a list of valid values.242243Example:244245.. click:example::246247 @click.command()248 @click.option('--hash-type', type=click.Choice(['md5', 'sha1']))249 def digest(hash_type):250 click.echo(hash_type)251252What it looks like:253254.. click:run::255256 invoke(digest, args=['--hash-type=md5'])257 println()258 invoke(digest, args=['--hash-type=foo'])259 println()260 invoke(digest, args=['--help'])261262.. _option-prompting:263264Prompting265---------266267In some cases, you want parameters that can be provided from the command line,268but if not provided, ask for user input instead. This can be implemented with269Click by defining a prompt string.270271Example:272273.. click:example::274275 @click.command()276 @click.option('--name', prompt=True)277 def hello(name):278 click.echo('Hello %s!' % name)279280And what it looks like:281282.. click:run::283284 invoke(hello, args=['--name=John'])285 invoke(hello, input=['John'])286287If you are not happy with the default prompt string, you can ask for288a different one:289290.. click:example::291292 @click.command()293 @click.option('--name', prompt='Your name please')294 def hello(name):295 click.echo('Hello %s!' % name)296297What it looks like:298299.. click:run::300301 invoke(hello, input=['John'])302303Password Prompts304----------------305306Click also supports hidden prompts and asking for confirmation. This is307useful for password input:308309.. click:example::310311 @click.command()312 @click.option('--password', prompt=True, hide_input=True,313 confirmation_prompt=True)314 def encrypt(password):315 click.echo('Encrypting password to %s' % password.encode('rot13'))316317What it looks like:318319.. click:run::320321 invoke(encrypt, input=['secret', 'secret'])322323Because this combination of parameters is quite common, this can also be324replaced with the :func:`password_option` decorator:325326.. click:example::327328 @click.command()329 @click.password_option()330 def encrypt(password):331 click.echo('Encrypting password to %s' % password.encode('rot13'))332333Dynamic Defaults for Prompts334----------------------------335336The ``auto_envvar_prefix`` and ``default_map`` options for the context337allow the program to read option values from the environment or a338configuration file. However, this overrides the prompting mechanism, so339that the user does not get the option to change the value interactively.340341If you want to let the user configure the default value, but still be342prompted if the option isn't specified on the command line, you can do so343by supplying a callable as the default value. For example, to get a default344from the environment:345346.. click:example::347348 @click.command()349 @click.option('--username', prompt=True,350 default=lambda: os.environ.get('USER', ''))351 def hello(username):352 print("Hello,", username)353354Callbacks and Eager Options355---------------------------356357Sometimes, you want a parameter to completely change the execution flow.358For instance, this is the case when you want to have a ``--version``359parameter that prints out the version and then exits the application.360361Note: an actual implementation of a ``--version`` parameter that is362reusable is available in Click as :func:`click.version_option`. The code363here is merely an example of how to implement such a flag.364365In such cases, you need two concepts: eager parameters and a callback. An366eager parameter is a parameter that is handled before others, and a367callback is what executes after the parameter is handled. The eagerness368is necessary so that an earlier required parameter does not produce an369error message. For instance, if ``--version`` was not eager and a370parameter ``--foo`` was required and defined before, you would need to371specify it for ``--version`` to work. For more information, see372:ref:`callback-evaluation-order`.373374A callback is a function that is invoked with two parameters: the current375:class:`Context` and the value. The context provides some useful features376such as quitting the application and gives access to other already377processed parameters.378379Here an example for a ``--version`` flag:380381.. click:example::382383 def print_version(ctx, param, value):384 if not value or ctx.resilient_parsing:385 return386 click.echo('Version 1.0')387 ctx.exit()388389 @click.command()390 @click.option('--version', is_flag=True, callback=print_version,391 expose_value=False, is_eager=True)392 def hello():393 click.echo('Hello World!')394395The `expose_value` parameter prevents the pretty pointless ``version``396parameter from being passed to the callback. If that was not specified, a397boolean would be passed to the `hello` script. The `resilient_parsing`398flag is applied to the context if Click wants to parse the command line399without any destructive behavior that would change the execution flow. In400this case, because we would exit the program, we instead do nothing.401402What it looks like:403404.. click:run::405406 invoke(hello)407 invoke(hello, args=['--version'])408409.. admonition:: Callback Signature Changes410411 In Click 2.0 the signature for callbacks changed. For more412 information about these changes see :ref:`upgrade-to-2.0`.413414Yes Parameters415--------------416417For dangerous operations, it's very useful to be able to ask a user for418confirmation. This can be done by adding a boolean ``--yes`` flag and419asking for confirmation if the user did not provide it and to fail in a420callback:421422.. click:example::423424 def abort_if_false(ctx, param, value):425 if not value:426 ctx.abort()427428 @click.command()429 @click.option('--yes', is_flag=True, callback=abort_if_false,430 expose_value=False,431 prompt='Are you sure you want to drop the db?')432 def dropdb():433 click.echo('Dropped all tables!')434435And what it looks like on the command line:436437.. click:run::438439 invoke(dropdb, input=['n'])440 invoke(dropdb, args=['--yes'])441442Because this combination of parameters is quite common, this can also be443replaced with the :func:`confirmation_option` decorator:444445.. click:example::446447 @click.command()448 @click.confirmation_option(help='Are you sure you want to drop the db?')449 def dropdb():450 click.echo('Dropped all tables!')451452.. admonition:: Callback Signature Changes453454 In Click 2.0 the signature for callbacks changed. For more455 information about these changes see :ref:`upgrade-to-2.0`.456457Values from Environment Variables458---------------------------------459460A very useful feature of Click is the ability to accept parameters from461environment variables in addition to regular parameters. This allows462tools to be automated much easier. For instance, you might want to pass463a configuration file with a ``--config`` parameter but also support exporting464a ``TOOL_CONFIG=hello.cfg`` key-value pair for a nicer development465experience.466467This is supported by Click in two ways. One is to automatically build468environment variables which is supported for options only. To enable this469feature, the ``auto_envvar_prefix`` parameter needs to be passed to the470script that is invoked. Each command and parameter is then added as an471uppercase underscore-separated variable. If you have a subcommand472called ``foo`` taking an option called ``bar`` and the prefix is473``MY_TOOL``, then the variable is ``MY_TOOL_FOO_BAR``.474475Example usage:476477.. click:example::478479 @click.command()480 @click.option('--username')481 def greet(username):482 click.echo('Hello %s!' % username)483484 if __name__ == '__main__':485 greet(auto_envvar_prefix='GREETER')486487And from the command line:488489.. click:run::490491 invoke(greet, env={'GREETER_USERNAME': 'john'},492 auto_envvar_prefix='GREETER')493494The second option is to manually pull values in from specific environment495variables by defining the name of the environment variable on the option.496497Example usage:498499.. click:example::500501 @click.command()502 @click.option('--username', envvar='USERNAME')503 def greet(username):504 click.echo('Hello %s!' % username)505506 if __name__ == '__main__':507 greet()508509And from the command line:510511.. click:run::512513 invoke(greet, env={'USERNAME': 'john'})514515In that case it can also be a list of different environment variables516where the first one is picked.517518Multiple Values from Environment Values519---------------------------------------520521As options can accept multiple values, pulling in such values from522environment variables (which are strings) is a bit more complex. The way523Click solves this is by leaving it up to the type to customize this524behavior. For both ``multiple`` and ``nargs`` with values other than525``1``, Click will invoke the :meth:`ParamType.split_envvar_value` method to526perform the splitting.527528The default implementation for all types is to split on whitespace. The529exceptions to this rule are the :class:`File` and :class:`Path` types530which both split according to the operating system's path splitting rules.531On Unix systems like Linux and OS X, the splitting happens for those on532every colon (``:``), and for Windows, on every semicolon (``;``).533534Example usage:535536.. click:example::537538 @click.command()539 @click.option('paths', '--path', envvar='PATHS', multiple=True,540 type=click.Path())541 def perform(paths):542 for path in paths:543 click.echo(path)544545 if __name__ == '__main__':546 perform()547548And from the command line:549550.. click:run::551552 import os553 invoke(perform, env={'PATHS': './foo/bar%s./test' % os.path.pathsep})554555Other Prefix Characters556-----------------------557558Click can deal with alternative prefix characters other than ``-`` for559options. This is for instance useful if you want to handle slashes as560parameters ``/`` or something similar. Note that this is strongly561discouraged in general because Click wants developers to stay close to562POSIX semantics. However in certain situations this can be useful:563564.. click:example::565566 @click.command()567 @click.option('+w/-w')568 def chmod(w):569 click.echo('writable=%s' % w)570571 if __name__ == '__main__':572 chmod()573574And from the command line:575576.. click:run::577578 invoke(chmod, args=['+w'])579 invoke(chmod, args=['-w'])580581Note that if you are using ``/`` as prefix character and you want to use a582boolean flag you need to separate it with ``;`` instead of ``/``:583584.. click:example::585586 @click.command()587 @click.option('/debug;/no-debug')588 def log(debug):589 click.echo('debug=%s' % debug)590591 if __name__ == '__main__':592 log()593594.. _ranges:595596Range Options597-------------598599A special mention should go to the :class:`IntRange` type, which works very600similarly to the :data:`INT` type, but restricts the value to fall into a601specific range (inclusive on both edges). It has two modes:602603- the default mode (non-clamping mode) where a value that falls outside604 of the range will cause an error.605- an optional clamping mode where a value that falls outside of the606 range will be clamped. This means that a range of ``0-5`` would607 return ``5`` for the value ``10`` or ``0`` for the value ``-1`` (for608 example).609610Example:611612.. click:example::613614 @click.command()615 @click.option('--count', type=click.IntRange(0, 20, clamp=True))616 @click.option('--digit', type=click.IntRange(0, 10))617 def repeat(count, digit):618 click.echo(str(digit) * count)619620 if __name__ == '__main__':621 repeat()622623And from the command line:624625.. click:run::626627 invoke(repeat, args=['--count=1000', '--digit=5'])628 invoke(repeat, args=['--count=1000', '--digit=12'])629630If you pass ``None`` for any of the edges, it means that the range is open631at that side.632633Callbacks for Validation634------------------------635636.. versionchanged:: 2.0637638If you want to apply custom validation logic, you can do this in the639parameter callbacks. These callbacks can both modify values as well as640raise errors if the validation does not work.641642In Click 1.0, you can only raise the :exc:`UsageError` but starting with643Click 2.0, you can also raise the :exc:`BadParameter` error, which has the644added advantage that it will automatically format the error message to645also contain the parameter name.646647Example:648649.. click:example::650651 def validate_rolls(ctx, param, value):652 try:653 rolls, dice = map(int, value.split('d', 2))654 return (dice, rolls)655 except ValueError:656 raise click.BadParameter('rolls need to be in format NdM')657658 @click.command()659 @click.option('--rolls', callback=validate_rolls, default='1d6')660 def roll(rolls):661 click.echo('Rolling a %d-sided dice %d time(s)' % rolls)662663 if __name__ == '__main__':664 roll()665666And what it looks like:667668.. click:run::669670 invoke(roll, args=['--rolls=42'])671 println()672 invoke(roll, args=['--rolls=2d12'])