options.rst
This file
Path
docs/options.rst
705 lines · 19.3 KiB
Last changed by
Merge pull request #799 from ericfrederich/option_namesMarkus Unterwaditzerbefore adoptione634d7f
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`. Unless a name is explicitly specified, the name of the20parameter is the first long option defined; otherwise the first short one is21used.2223.. click:example::2425 @click.command()26 @click.option('--n', default=1)27 def dots(n):28 click.echo('.' * n)2930.. click:example::3132 # How to use a Python reserved word such as `from` as a parameter33 @click.command()34 @click.option('--from', '-f', '_from')35 @click.option('--to', '-t')36 def reserved_param_name(_from, to):37 click.echo('from %s to %s' % (_from, to))3839And on the command line:4041.. click:run::4243 invoke(dots, args=['--n=2'])4445In this case the option is of type :data:`INT` because the default value46is an integer.4748Multi Value Options49-------------------5051Sometimes, you have options that take more than one argument. For options,52only a fixed number of arguments is supported. This can be configured by53the ``nargs`` parameter. The values are then stored as a tuple.5455.. click:example::5657 @click.command()58 @click.option('--pos', nargs=2, type=float)59 def findme(pos):60 click.echo('%s / %s' % pos)6162And on the command line:6364.. click:run::6566 invoke(findme, args=['--pos', '2.0', '3.0'])6768.. _tuple-type:6970Tuples as Multi Value Options71-----------------------------7273.. versionadded:: 4.07475As you can see that by using `nargs` set to a specific number each item in76the resulting tuple is of the same type. This might not be what you want.77Commonly you might want to use different types for different indexes in78the tuple. For this you can directly specify a tuple as type:7980.. click:example::8182 @click.command()83 @click.option('--item', type=(unicode, int))84 def putitem(item):85 click.echo('name=%s id=%d' % item)8687And on the command line:8889.. click:run::9091 invoke(putitem, args=['--item', 'peter', '1338'])9293By using a tuple literal as type, `nargs` gets automatically set to the94length of the tuple and the :class:`click.Tuple` type is automatically95used. The above example is thus equivalent to this:9697.. click:example::9899 @click.command()100 @click.option('--item', nargs=2, type=click.Tuple([unicode, int]))101 def putitem(item):102 click.echo('name=%s id=%d' % item)103104Multiple Options105----------------106107Similarly to ``nargs``, there is also the case of wanting to support a108parameter being provided multiple times to and have all values recorded --109not just the last one. For instance, ``git commit -m foo -m bar`` would110record two lines for the commit message: ``foo`` and ``bar``. This can be111accomplished with the ``multiple`` flag:112113Example:114115.. click:example::116117 @click.command()118 @click.option('--message', '-m', multiple=True)119 def commit(message):120 click.echo('\n'.join(message))121122And on the command line:123124.. click:run::125126 invoke(commit, args=['-m', 'foo', '-m', 'bar'])127128Counting129--------130131In some very rare circumstances, it is interesting to use the repetition132of options to count an integer up. This can be used for verbosity flags,133for instance:134135.. click:example::136137 @click.command()138 @click.option('-v', '--verbose', count=True)139 def log(verbose):140 click.echo('Verbosity: %s' % verbose)141142And on the command line:143144.. click:run::145146 invoke(log, args=['-vvv'])147148Boolean Flags149-------------150151Boolean flags are options that can be enabled or disabled. This can be152accomplished by defining two flags in one go separated by a slash (``/``)153for enabling or disabling the option. (If a slash is in an option string,154Click automatically knows that it's a boolean flag and will pass155``is_flag=True`` implicitly.) Click always wants you to provide an enable156and disable flag so that you can change the default later.157158Example:159160.. click:example::161162 import sys163164 @click.command()165 @click.option('--shout/--no-shout', default=False)166 def info(shout):167 rv = sys.platform168 if shout:169 rv = rv.upper() + '!!!!111'170 click.echo(rv)171172And on the command line:173174.. click:run::175176 invoke(info, args=['--shout'])177 invoke(info, args=['--no-shout'])178179If you really don't want an off-switch, you can just define one and180manually inform Click that something is a flag:181182.. click:example::183184 import sys185186 @click.command()187 @click.option('--shout', is_flag=True)188 def info(shout):189 rv = sys.platform190 if shout:191 rv = rv.upper() + '!!!!111'192 click.echo(rv)193194And on the command line:195196.. click:run::197198 invoke(info, args=['--shout'])199200Note that if a slash is contained in your option already (for instance, if201you use Windows-style parameters where ``/`` is the prefix character), you202can alternatively split the parameters through ``;`` instead:203204.. click:example::205206 @click.command()207 @click.option('/debug;/no-debug')208 def log(debug):209 click.echo('debug=%s' % debug)210211 if __name__ == '__main__':212 log()213214.. versionchanged:: 6.0215216If you want to define an alias for the second option only, then you will217need to use leading whitespace to disambiguate the format string:218219Example:220221.. click:example::222223 import sys224225 @click.command()226 @click.option('--shout/--no-shout', ' /-S', default=False)227 def info(shout):228 rv = sys.platform229 if shout:230 rv = rv.upper() + '!!!!111'231 click.echo(rv)232233.. click:run::234235 invoke(info, args=['--help'])236237Feature Switches238----------------239240In addition to boolean flags, there are also feature switches. These are241implemented by setting multiple options to the same parameter name and242defining a flag value. Note that by providing the ``flag_value`` parameter,243Click will implicitly set ``is_flag=True``.244245To set a default flag, assign a value of `True` to the flag that should be246the default.247248.. click:example::249250 import sys251252 @click.command()253 @click.option('--upper', 'transformation', flag_value='upper',254 default=True)255 @click.option('--lower', 'transformation', flag_value='lower')256 def info(transformation):257 click.echo(getattr(sys.platform, transformation)())258259And on the command line:260261.. click:run::262263 invoke(info, args=['--upper'])264 invoke(info, args=['--lower'])265 invoke(info)266267.. _choice-opts:268269Choice Options270--------------271272Sometimes, you want to have a parameter be a choice of a list of values.273In that case you can use :class:`Choice` type. It can be instantiated274with a list of valid values.275276Example:277278.. click:example::279280 @click.command()281 @click.option('--hash-type', type=click.Choice(['md5', 'sha1']))282 def digest(hash_type):283 click.echo(hash_type)284285What it looks like:286287.. click:run::288289 invoke(digest, args=['--hash-type=md5'])290 println()291 invoke(digest, args=['--hash-type=foo'])292 println()293 invoke(digest, args=['--help'])294295.. _option-prompting:296297Prompting298---------299300In some cases, you want parameters that can be provided from the command line,301but if not provided, ask for user input instead. This can be implemented with302Click by defining a prompt string.303304Example:305306.. click:example::307308 @click.command()309 @click.option('--name', prompt=True)310 def hello(name):311 click.echo('Hello %s!' % name)312313And what it looks like:314315.. click:run::316317 invoke(hello, args=['--name=John'])318 invoke(hello, input=['John'])319320If you are not happy with the default prompt string, you can ask for321a different one:322323.. click:example::324325 @click.command()326 @click.option('--name', prompt='Your name please')327 def hello(name):328 click.echo('Hello %s!' % name)329330What it looks like:331332.. click:run::333334 invoke(hello, input=['John'])335336Password Prompts337----------------338339Click also supports hidden prompts and asking for confirmation. This is340useful for password input:341342.. click:example::343344 @click.command()345 @click.option('--password', prompt=True, hide_input=True,346 confirmation_prompt=True)347 def encrypt(password):348 click.echo('Encrypting password to %s' % password.encode('rot13'))349350What it looks like:351352.. click:run::353354 invoke(encrypt, input=['secret', 'secret'])355356Because this combination of parameters is quite common, this can also be357replaced with the :func:`password_option` decorator:358359.. click:example::360361 @click.command()362 @click.password_option()363 def encrypt(password):364 click.echo('Encrypting password to %s' % password.encode('rot13'))365366Dynamic Defaults for Prompts367----------------------------368369The ``auto_envvar_prefix`` and ``default_map`` options for the context370allow the program to read option values from the environment or a371configuration file. However, this overrides the prompting mechanism, so372that the user does not get the option to change the value interactively.373374If you want to let the user configure the default value, but still be375prompted if the option isn't specified on the command line, you can do so376by supplying a callable as the default value. For example, to get a default377from the environment:378379.. click:example::380381 @click.command()382 @click.option('--username', prompt=True,383 default=lambda: os.environ.get('USER', ''))384 def hello(username):385 print("Hello,", username)386387Callbacks and Eager Options388---------------------------389390Sometimes, you want a parameter to completely change the execution flow.391For instance, this is the case when you want to have a ``--version``392parameter that prints out the version and then exits the application.393394Note: an actual implementation of a ``--version`` parameter that is395reusable is available in Click as :func:`click.version_option`. The code396here is merely an example of how to implement such a flag.397398In such cases, you need two concepts: eager parameters and a callback. An399eager parameter is a parameter that is handled before others, and a400callback is what executes after the parameter is handled. The eagerness401is necessary so that an earlier required parameter does not produce an402error message. For instance, if ``--version`` was not eager and a403parameter ``--foo`` was required and defined before, you would need to404specify it for ``--version`` to work. For more information, see405:ref:`callback-evaluation-order`.406407A callback is a function that is invoked with two parameters: the current408:class:`Context` and the value. The context provides some useful features409such as quitting the application and gives access to other already410processed parameters.411412Here an example for a ``--version`` flag:413414.. click:example::415416 def print_version(ctx, param, value):417 if not value or ctx.resilient_parsing:418 return419 click.echo('Version 1.0')420 ctx.exit()421422 @click.command()423 @click.option('--version', is_flag=True, callback=print_version,424 expose_value=False, is_eager=True)425 def hello():426 click.echo('Hello World!')427428The `expose_value` parameter prevents the pretty pointless ``version``429parameter from being passed to the callback. If that was not specified, a430boolean would be passed to the `hello` script. The `resilient_parsing`431flag is applied to the context if Click wants to parse the command line432without any destructive behavior that would change the execution flow. In433this case, because we would exit the program, we instead do nothing.434435What it looks like:436437.. click:run::438439 invoke(hello)440 invoke(hello, args=['--version'])441442.. admonition:: Callback Signature Changes443444 In Click 2.0 the signature for callbacks changed. For more445 information about these changes see :ref:`upgrade-to-2.0`.446447Yes Parameters448--------------449450For dangerous operations, it's very useful to be able to ask a user for451confirmation. This can be done by adding a boolean ``--yes`` flag and452asking for confirmation if the user did not provide it and to fail in a453callback:454455.. click:example::456457 def abort_if_false(ctx, param, value):458 if not value:459 ctx.abort()460461 @click.command()462 @click.option('--yes', is_flag=True, callback=abort_if_false,463 expose_value=False,464 prompt='Are you sure you want to drop the db?')465 def dropdb():466 click.echo('Dropped all tables!')467468And what it looks like on the command line:469470.. click:run::471472 invoke(dropdb, input=['n'])473 invoke(dropdb, args=['--yes'])474475Because this combination of parameters is quite common, this can also be476replaced with the :func:`confirmation_option` decorator:477478.. click:example::479480 @click.command()481 @click.confirmation_option(prompt='Are you sure you want to drop the db?')482 def dropdb():483 click.echo('Dropped all tables!')484485.. admonition:: Callback Signature Changes486487 In Click 2.0 the signature for callbacks changed. For more488 information about these changes see :ref:`upgrade-to-2.0`.489490Values from Environment Variables491---------------------------------492493A very useful feature of Click is the ability to accept parameters from494environment variables in addition to regular parameters. This allows495tools to be automated much easier. For instance, you might want to pass496a configuration file with a ``--config`` parameter but also support exporting497a ``TOOL_CONFIG=hello.cfg`` key-value pair for a nicer development498experience.499500This is supported by Click in two ways. One is to automatically build501environment variables which is supported for options only. To enable this502feature, the ``auto_envvar_prefix`` parameter needs to be passed to the503script that is invoked. Each command and parameter is then added as an504uppercase underscore-separated variable. If you have a subcommand505called ``foo`` taking an option called ``bar`` and the prefix is506``MY_TOOL``, then the variable is ``MY_TOOL_FOO_BAR``.507508Example usage:509510.. click:example::511512 @click.command()513 @click.option('--username')514 def greet(username):515 click.echo('Hello %s!' % username)516517 if __name__ == '__main__':518 greet(auto_envvar_prefix='GREETER')519520And from the command line:521522.. click:run::523524 invoke(greet, env={'GREETER_USERNAME': 'john'},525 auto_envvar_prefix='GREETER')526527The second option is to manually pull values in from specific environment528variables by defining the name of the environment variable on the option.529530Example usage:531532.. click:example::533534 @click.command()535 @click.option('--username', envvar='USERNAME')536 def greet(username):537 click.echo('Hello %s!' % username)538539 if __name__ == '__main__':540 greet()541542And from the command line:543544.. click:run::545546 invoke(greet, env={'USERNAME': 'john'})547548In that case it can also be a list of different environment variables549where the first one is picked.550551Multiple Values from Environment Values552---------------------------------------553554As options can accept multiple values, pulling in such values from555environment variables (which are strings) is a bit more complex. The way556Click solves this is by leaving it up to the type to customize this557behavior. For both ``multiple`` and ``nargs`` with values other than558``1``, Click will invoke the :meth:`ParamType.split_envvar_value` method to559perform the splitting.560561The default implementation for all types is to split on whitespace. The562exceptions to this rule are the :class:`File` and :class:`Path` types563which both split according to the operating system's path splitting rules.564On Unix systems like Linux and OS X, the splitting happens for those on565every colon (``:``), and for Windows, on every semicolon (``;``).566567Example usage:568569.. click:example::570571 @click.command()572 @click.option('paths', '--path', envvar='PATHS', multiple=True,573 type=click.Path())574 def perform(paths):575 for path in paths:576 click.echo(path)577578 if __name__ == '__main__':579 perform()580581And from the command line:582583.. click:run::584585 import os586 invoke(perform, env={'PATHS': './foo/bar%s./test' % os.path.pathsep})587588Other Prefix Characters589-----------------------590591Click can deal with alternative prefix characters other than ``-`` for592options. This is for instance useful if you want to handle slashes as593parameters ``/`` or something similar. Note that this is strongly594discouraged in general because Click wants developers to stay close to595POSIX semantics. However in certain situations this can be useful:596597.. click:example::598599 @click.command()600 @click.option('+w/-w')601 def chmod(w):602 click.echo('writable=%s' % w)603604 if __name__ == '__main__':605 chmod()606607And from the command line:608609.. click:run::610611 invoke(chmod, args=['+w'])612 invoke(chmod, args=['-w'])613614Note that if you are using ``/`` as prefix character and you want to use a615boolean flag you need to separate it with ``;`` instead of ``/``:616617.. click:example::618619 @click.command()620 @click.option('/debug;/no-debug')621 def log(debug):622 click.echo('debug=%s' % debug)623624 if __name__ == '__main__':625 log()626627.. _ranges:628629Range Options630-------------631632A special mention should go to the :class:`IntRange` type, which works very633similarly to the :data:`INT` type, but restricts the value to fall into a634specific range (inclusive on both edges). It has two modes:635636- the default mode (non-clamping mode) where a value that falls outside637 of the range will cause an error.638- an optional clamping mode where a value that falls outside of the639 range will be clamped. This means that a range of ``0-5`` would640 return ``5`` for the value ``10`` or ``0`` for the value ``-1`` (for641 example).642643Example:644645.. click:example::646647 @click.command()648 @click.option('--count', type=click.IntRange(0, 20, clamp=True))649 @click.option('--digit', type=click.IntRange(0, 10))650 def repeat(count, digit):651 click.echo(str(digit) * count)652653 if __name__ == '__main__':654 repeat()655656And from the command line:657658.. click:run::659660 invoke(repeat, args=['--count=1000', '--digit=5'])661 invoke(repeat, args=['--count=1000', '--digit=12'])662663If you pass ``None`` for any of the edges, it means that the range is open664at that side.665666Callbacks for Validation667------------------------668669.. versionchanged:: 2.0670671If you want to apply custom validation logic, you can do this in the672parameter callbacks. These callbacks can both modify values as well as673raise errors if the validation does not work.674675In Click 1.0, you can only raise the :exc:`UsageError` but starting with676Click 2.0, you can also raise the :exc:`BadParameter` error, which has the677added advantage that it will automatically format the error message to678also contain the parameter name.679680Example:681682.. click:example::683684 def validate_rolls(ctx, param, value):685 try:686 rolls, dice = map(int, value.split('d', 2))687 return (dice, rolls)688 except ValueError:689 raise click.BadParameter('rolls need to be in format NdM')690691 @click.command()692 @click.option('--rolls', callback=validate_rolls, default='1d6')693 def roll(rolls):694 click.echo('Rolling a %d-sided dice %d time(s)' % rolls)695696 if __name__ == '__main__':697 roll()698699And what it looks like:700701.. click:run::702703 invoke(roll, args=['--rolls=42'])704 println()705 invoke(roll, args=['--rolls=2d12'])