options.rst
This file
Path
docs/options.rst
796 lines · 21.6 KiB
Last changed by
Merge pull request #1100 from pallets/sphinxDavid Lordbefore adoptionb1b8c48
History of this fileTake it
The walk stopped after 200 commits: lines older than 8ed2573 point at it.
Merge pull request #488 from RonnyPfannschmidt/fix-termioArmin Ronacherbefore adoption8ed2573
lines 1–12why, one step back1.. _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>`.12Merge pull request #1016 from dawran6/issue-725Dan Sullybefore adoptionc914686
lines 13–34why, one step back13Name Your Options14-----------------1516The naming rules can be found in :ref:`parameter_names`. In short, you17can refer the option **implicitly** by the longest dash-prefixed argument:1819.. click:example::2021 @click.command()22 @click.option('-s', '--string-to-echo')23 def echo(string_to_echo):24 click.echo(string_to_echo)2526Or, **explicitly**, by giving one non-dash-prefixed argument:2728.. click:example::2930 @click.command()31 @click.option('-s', '--string-to-echo', 'string')32 def echo(string):33 click.echo(string)34Merge pull request #488 from RonnyPfannschmidt/fix-termioArmin Ronacherbefore adoption8ed2573
lines 35–40why, one step back35Basic Value Options36-------------------3738The most basic option is a value option. These options accept one39argument which is a value. If no type is provided, the type of the default40value is used. If no default value is provided, the type is assumed to beMerge pull request #799 from ericfrederich/option_namesMarkus Unterwaditzerbefore adoptione634d7f
lines 41–42why, one step back41:data:`STRING`. Unless a name is explicitly specified, the name of the42parameter is the first long option defined; otherwise the first short one isMerge pull request #1022 from pallets/514-document-requiredDan Sullybefore adoptionb10c52a
lines 43–44why, one step back43used. By default, options are not required, however to make an option required,44simply pass in `required=True` as an argument to the decorator.Merge pull request #488 from RonnyPfannschmidt/fix-termioArmin Ronacherbefore adoption8ed2573
lines 45–49why, one step back4546.. click:example::4748 @click.command()49 @click.option('--n', default=1)Merge pull request #1022 from pallets/514-document-requiredDan Sullybefore adoptionb10c52a
lines 50–57why, one step back50 def dots(n):51 click.echo('.' * n)5253.. click:example::5455 # How to make an option required56 @click.command()57 @click.option('--n', required=True, type=int)Merge pull request #488 from RonnyPfannschmidt/fix-termioArmin Ronacherbefore adoption8ed2573
lines 58–59why, one step back58 def dots(n):59 click.echo('.' * n)Merge pull request #799 from ericfrederich/option_namesMarkus Unterwaditzerbefore adoptione634d7f
lines 60–64why, one step back6061.. click:example::6263 # How to use a Python reserved word such as `from` as a parameter64 @click.command()Follow PEP8 recommendation for param naming (#1073)Renne Rochabefore adoption03e0133
line 65why, one step back65 @click.option('--from', '-f', 'from_')Merge pull request #799 from ericfrederich/option_namesMarkus Unterwaditzerbefore adoptione634d7f
line 66why, one step back66 @click.option('--to', '-t')Follow PEP8 recommendation for param naming (#1073)Renne Rochabefore adoption03e0133
lines 67–68why, one step back67 def reserved_param_name(from_, to):68 click.echo('from %s to %s' % (from_, to))Merge pull request #488 from RonnyPfannschmidt/fix-termioArmin Ronacherbefore adoption8ed2573
lines 69–78why, one step back6970And on the command line:7172.. click:run::7374 invoke(dots, args=['--n=2'])7576In this case the option is of type :data:`INT` because the default value77is an integer.78Merge pull request #996 from dougharris/lambda-844-547Dan Sullybefore adoptionbc53a96
lines 79–91why, one step back79To show the default values when showing command help, use ``show_default=True``8081.. click:example::8283 @click.command()84 @click.option('--n', default=1, show_default=True)85 def dots(n):86 click.echo('.' * n)8788.. click:run::8990 invoke(dots, args=['--help'])91Merge pull request #488 from RonnyPfannschmidt/fix-termioArmin Ronacherbefore adoption8ed2573
lines 92–126why, one step back92Multi Value Options93-------------------9495Sometimes, you have options that take more than one argument. For options,96only a fixed number of arguments is supported. This can be configured by97the ``nargs`` parameter. The values are then stored as a tuple.9899.. click:example::100101 @click.command()102 @click.option('--pos', nargs=2, type=float)103 def findme(pos):104 click.echo('%s / %s' % pos)105106And on the command line:107108.. click:run::109110 invoke(findme, args=['--pos', '2.0', '3.0'])111112.. _tuple-type:113114Tuples as Multi Value Options115-----------------------------116117.. versionadded:: 4.0118119As you can see that by using `nargs` set to a specific number each item in120the resulting tuple is of the same type. This might not be what you want.121Commonly you might want to use different types for different indexes in122the tuple. For this you can directly specify a tuple as type:123124.. click:example::125126 @click.command()Merge pull request #1100 from pallets/sphinxDavid Lordbefore adoptionb1b8c48
line 127why, one step back127 @click.option('--item', type=(str, int))Merge pull request #488 from RonnyPfannschmidt/fix-termioArmin Ronacherbefore adoption8ed2573
lines 128–143why, one step back128 def putitem(item):129 click.echo('name=%s id=%d' % item)130131And on the command line:132133.. click:run::134135 invoke(putitem, args=['--item', 'peter', '1338'])136137By using a tuple literal as type, `nargs` gets automatically set to the138length of the tuple and the :class:`click.Tuple` type is automatically139used. The above example is thus equivalent to this:140141.. click:example::142143 @click.command()Merge pull request #1100 from pallets/sphinxDavid Lordbefore adoptionb1b8c48
line 144why, one step back144 @click.option('--item', nargs=2, type=click.Tuple([str, int]))Merge pull request #488 from RonnyPfannschmidt/fix-termioArmin Ronacherbefore adoption8ed2573
lines 145–338why, one step back145 def putitem(item):146 click.echo('name=%s id=%d' % item)147148Multiple Options149----------------150151Similarly to ``nargs``, there is also the case of wanting to support a152parameter being provided multiple times to and have all values recorded --153not just the last one. For instance, ``git commit -m foo -m bar`` would154record two lines for the commit message: ``foo`` and ``bar``. This can be155accomplished with the ``multiple`` flag:156157Example:158159.. click:example::160161 @click.command()162 @click.option('--message', '-m', multiple=True)163 def commit(message):164 click.echo('\n'.join(message))165166And on the command line:167168.. click:run::169170 invoke(commit, args=['-m', 'foo', '-m', 'bar'])171172Counting173--------174175In some very rare circumstances, it is interesting to use the repetition176of options to count an integer up. This can be used for verbosity flags,177for instance:178179.. click:example::180181 @click.command()182 @click.option('-v', '--verbose', count=True)183 def log(verbose):184 click.echo('Verbosity: %s' % verbose)185186And on the command line:187188.. click:run::189190 invoke(log, args=['-vvv'])191192Boolean Flags193-------------194195Boolean flags are options that can be enabled or disabled. This can be196accomplished by defining two flags in one go separated by a slash (``/``)197for enabling or disabling the option. (If a slash is in an option string,198Click automatically knows that it's a boolean flag and will pass199``is_flag=True`` implicitly.) Click always wants you to provide an enable200and disable flag so that you can change the default later.201202Example:203204.. click:example::205206 import sys207208 @click.command()209 @click.option('--shout/--no-shout', default=False)210 def info(shout):211 rv = sys.platform212 if shout:213 rv = rv.upper() + '!!!!111'214 click.echo(rv)215216And on the command line:217218.. click:run::219220 invoke(info, args=['--shout'])221 invoke(info, args=['--no-shout'])222223If you really don't want an off-switch, you can just define one and224manually inform Click that something is a flag:225226.. click:example::227228 import sys229230 @click.command()231 @click.option('--shout', is_flag=True)232 def info(shout):233 rv = sys.platform234 if shout:235 rv = rv.upper() + '!!!!111'236 click.echo(rv)237238And on the command line:239240.. click:run::241242 invoke(info, args=['--shout'])243244Note that if a slash is contained in your option already (for instance, if245you use Windows-style parameters where ``/`` is the prefix character), you246can alternatively split the parameters through ``;`` instead:247248.. click:example::249250 @click.command()251 @click.option('/debug;/no-debug')252 def log(debug):253 click.echo('debug=%s' % debug)254255 if __name__ == '__main__':256 log()257258.. versionchanged:: 6.0259260If you want to define an alias for the second option only, then you will261need to use leading whitespace to disambiguate the format string:262263Example:264265.. click:example::266267 import sys268269 @click.command()270 @click.option('--shout/--no-shout', ' /-S', default=False)271 def info(shout):272 rv = sys.platform273 if shout:274 rv = rv.upper() + '!!!!111'275 click.echo(rv)276277.. click:run::278279 invoke(info, args=['--help'])280281Feature Switches282----------------283284In addition to boolean flags, there are also feature switches. These are285implemented by setting multiple options to the same parameter name and286defining a flag value. Note that by providing the ``flag_value`` parameter,287Click will implicitly set ``is_flag=True``.288289To set a default flag, assign a value of `True` to the flag that should be290the default.291292.. click:example::293294 import sys295296 @click.command()297 @click.option('--upper', 'transformation', flag_value='upper',298 default=True)299 @click.option('--lower', 'transformation', flag_value='lower')300 def info(transformation):301 click.echo(getattr(sys.platform, transformation)())302303And on the command line:304305.. click:run::306307 invoke(info, args=['--upper'])308 invoke(info, args=['--lower'])309 invoke(info)310311.. _choice-opts:312313Choice Options314--------------315316Sometimes, you want to have a parameter be a choice of a list of values.317In that case you can use :class:`Choice` type. It can be instantiated318with a list of valid values.319320Example:321322.. click:example::323324 @click.command()325 @click.option('--hash-type', type=click.Choice(['md5', 'sha1']))326 def digest(hash_type):327 click.echo(hash_type)328329What it looks like:330331.. click:run::332333 invoke(digest, args=['--hash-type=md5'])334 println()335 invoke(digest, args=['--hash-type=foo'])336 println()337 invoke(digest, args=['--help'])338Improve docs for Choice type (addresses issue #892) (#900)Stefan Scherfkebefore adoptionc67daae
lines 339–343why, one step back339.. note::340341 You should only pass the choices as list or tuple. Other iterables (like342 generators) may lead to surprising results.343Merge pull request #488 from RonnyPfannschmidt/fix-termioArmin Ronacherbefore adoption8ed2573
lines 344–434why, one step back344.. _option-prompting:345346Prompting347---------348349In some cases, you want parameters that can be provided from the command line,350but if not provided, ask for user input instead. This can be implemented with351Click by defining a prompt string.352353Example:354355.. click:example::356357 @click.command()358 @click.option('--name', prompt=True)359 def hello(name):360 click.echo('Hello %s!' % name)361362And what it looks like:363364.. click:run::365366 invoke(hello, args=['--name=John'])367 invoke(hello, input=['John'])368369If you are not happy with the default prompt string, you can ask for370a different one:371372.. click:example::373374 @click.command()375 @click.option('--name', prompt='Your name please')376 def hello(name):377 click.echo('Hello %s!' % name)378379What it looks like:380381.. click:run::382383 invoke(hello, input=['John'])384385Password Prompts386----------------387388Click also supports hidden prompts and asking for confirmation. This is389useful for password input:390391.. click:example::392393 @click.command()394 @click.option('--password', prompt=True, hide_input=True,395 confirmation_prompt=True)396 def encrypt(password):397 click.echo('Encrypting password to %s' % password.encode('rot13'))398399What it looks like:400401.. click:run::402403 invoke(encrypt, input=['secret', 'secret'])404405Because this combination of parameters is quite common, this can also be406replaced with the :func:`password_option` decorator:407408.. click:example::409410 @click.command()411 @click.password_option()412 def encrypt(password):413 click.echo('Encrypting password to %s' % password.encode('rot13'))414415Dynamic Defaults for Prompts416----------------------------417418The ``auto_envvar_prefix`` and ``default_map`` options for the context419allow the program to read option values from the environment or a420configuration file. However, this overrides the prompting mechanism, so421that the user does not get the option to change the value interactively.422423If you want to let the user configure the default value, but still be424prompted if the option isn't specified on the command line, you can do so425by supplying a callable as the default value. For example, to get a default426from the environment:427428.. click:example::429430 @click.command()431 @click.option('--username', prompt=True,432 default=lambda: os.environ.get('USER', ''))433 def hello(username):434 print("Hello,", username)Merge pull request #996 from dougharris/lambda-844-547Dan Sullybefore adoptionbc53a96
lines 435–449why, one step back435436To describe what the default value will be, set it in ``show_default``.437438.. click:example::439440 @click.command()441 @click.option('--username', prompt=True,442 default=lambda: os.environ.get('USER', ''),443 show_default='current user')444 def hello(username):445 print("Hello,", username)446447.. click:run::448449 invoke(hello, args=['--help'])Merge pull request #488 from RonnyPfannschmidt/fix-termioArmin Ronacherbefore adoption8ed2573
lines 450–590why, one step back450451Callbacks and Eager Options452---------------------------453454Sometimes, you want a parameter to completely change the execution flow.455For instance, this is the case when you want to have a ``--version``456parameter that prints out the version and then exits the application.457458Note: an actual implementation of a ``--version`` parameter that is459reusable is available in Click as :func:`click.version_option`. The code460here is merely an example of how to implement such a flag.461462In such cases, you need two concepts: eager parameters and a callback. An463eager parameter is a parameter that is handled before others, and a464callback is what executes after the parameter is handled. The eagerness465is necessary so that an earlier required parameter does not produce an466error message. For instance, if ``--version`` was not eager and a467parameter ``--foo`` was required and defined before, you would need to468specify it for ``--version`` to work. For more information, see469:ref:`callback-evaluation-order`.470471A callback is a function that is invoked with two parameters: the current472:class:`Context` and the value. The context provides some useful features473such as quitting the application and gives access to other already474processed parameters.475476Here an example for a ``--version`` flag:477478.. click:example::479480 def print_version(ctx, param, value):481 if not value or ctx.resilient_parsing:482 return483 click.echo('Version 1.0')484 ctx.exit()485486 @click.command()487 @click.option('--version', is_flag=True, callback=print_version,488 expose_value=False, is_eager=True)489 def hello():490 click.echo('Hello World!')491492The `expose_value` parameter prevents the pretty pointless ``version``493parameter from being passed to the callback. If that was not specified, a494boolean would be passed to the `hello` script. The `resilient_parsing`495flag is applied to the context if Click wants to parse the command line496without any destructive behavior that would change the execution flow. In497this case, because we would exit the program, we instead do nothing.498499What it looks like:500501.. click:run::502503 invoke(hello)504 invoke(hello, args=['--version'])505506.. admonition:: Callback Signature Changes507508 In Click 2.0 the signature for callbacks changed. For more509 information about these changes see :ref:`upgrade-to-2.0`.510511Yes Parameters512--------------513514For dangerous operations, it's very useful to be able to ask a user for515confirmation. This can be done by adding a boolean ``--yes`` flag and516asking for confirmation if the user did not provide it and to fail in a517callback:518519.. click:example::520521 def abort_if_false(ctx, param, value):522 if not value:523 ctx.abort()524525 @click.command()526 @click.option('--yes', is_flag=True, callback=abort_if_false,527 expose_value=False,528 prompt='Are you sure you want to drop the db?')529 def dropdb():530 click.echo('Dropped all tables!')531532And what it looks like on the command line:533534.. click:run::535536 invoke(dropdb, input=['n'])537 invoke(dropdb, args=['--yes'])538539Because this combination of parameters is quite common, this can also be540replaced with the :func:`confirmation_option` decorator:541542.. click:example::543544 @click.command()545 @click.confirmation_option(prompt='Are you sure you want to drop the db?')546 def dropdb():547 click.echo('Dropped all tables!')548549.. admonition:: Callback Signature Changes550551 In Click 2.0 the signature for callbacks changed. For more552 information about these changes see :ref:`upgrade-to-2.0`.553554Values from Environment Variables555---------------------------------556557A very useful feature of Click is the ability to accept parameters from558environment variables in addition to regular parameters. This allows559tools to be automated much easier. For instance, you might want to pass560a configuration file with a ``--config`` parameter but also support exporting561a ``TOOL_CONFIG=hello.cfg`` key-value pair for a nicer development562experience.563564This is supported by Click in two ways. One is to automatically build565environment variables which is supported for options only. To enable this566feature, the ``auto_envvar_prefix`` parameter needs to be passed to the567script that is invoked. Each command and parameter is then added as an568uppercase underscore-separated variable. If you have a subcommand569called ``foo`` taking an option called ``bar`` and the prefix is570``MY_TOOL``, then the variable is ``MY_TOOL_FOO_BAR``.571572Example usage:573574.. click:example::575576 @click.command()577 @click.option('--username')578 def greet(username):579 click.echo('Hello %s!' % username)580581 if __name__ == '__main__':582 greet(auto_envvar_prefix='GREETER')583584And from the command line:585586.. click:run::587588 invoke(greet, env={'GREETER_USERNAME': 'john'},589 auto_envvar_prefix='GREETER')590Merge pull request #1011 from dougharris/auto-envvar-501Dan Sullybefore adoption0650d36
lines 591–617why, one step back591When using ``auto_envvar_prefix`` with command groups, the command name needs592to be included in the environment variable, between the prefix and the parameter name, *i.e.* *PREFIX_COMMAND_VARIABLE*.593594Example:595596.. click:example::597598 @click.group()599 @click.option('--debug/--no-debug')600 def cli(debug):601 click.echo('Debug mode is %s' % ('on' if debug else 'off'))602603 @cli.command()604 @click.option('--username')605 def greet(username):606 click.echo('Hello %s!' % username)607608 if __name__ == '__main__':609 cli(auto_envvar_prefix='GREETER')610611.. click:run::612613 invoke(cli, args=['greet',],614 env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},615 auto_envvar_prefix='GREETER')616617Merge pull request #488 from RonnyPfannschmidt/fix-termioArmin Ronacherbefore adoption8ed2573
lines 618–796why, one step back618The second option is to manually pull values in from specific environment619variables by defining the name of the environment variable on the option.620621Example usage:622623.. click:example::624625 @click.command()626 @click.option('--username', envvar='USERNAME')627 def greet(username):628 click.echo('Hello %s!' % username)629630 if __name__ == '__main__':631 greet()632633And from the command line:634635.. click:run::636637 invoke(greet, env={'USERNAME': 'john'})638639In that case it can also be a list of different environment variables640where the first one is picked.641642Multiple Values from Environment Values643---------------------------------------644645As options can accept multiple values, pulling in such values from646environment variables (which are strings) is a bit more complex. The way647Click solves this is by leaving it up to the type to customize this648behavior. For both ``multiple`` and ``nargs`` with values other than649``1``, Click will invoke the :meth:`ParamType.split_envvar_value` method to650perform the splitting.651652The default implementation for all types is to split on whitespace. The653exceptions to this rule are the :class:`File` and :class:`Path` types654which both split according to the operating system's path splitting rules.655On Unix systems like Linux and OS X, the splitting happens for those on656every colon (``:``), and for Windows, on every semicolon (``;``).657658Example usage:659660.. click:example::661662 @click.command()663 @click.option('paths', '--path', envvar='PATHS', multiple=True,664 type=click.Path())665 def perform(paths):666 for path in paths:667 click.echo(path)668669 if __name__ == '__main__':670 perform()671672And from the command line:673674.. click:run::675676 import os677 invoke(perform, env={'PATHS': './foo/bar%s./test' % os.path.pathsep})678679Other Prefix Characters680-----------------------681682Click can deal with alternative prefix characters other than ``-`` for683options. This is for instance useful if you want to handle slashes as684parameters ``/`` or something similar. Note that this is strongly685discouraged in general because Click wants developers to stay close to686POSIX semantics. However in certain situations this can be useful:687688.. click:example::689690 @click.command()691 @click.option('+w/-w')692 def chmod(w):693 click.echo('writable=%s' % w)694695 if __name__ == '__main__':696 chmod()697698And from the command line:699700.. click:run::701702 invoke(chmod, args=['+w'])703 invoke(chmod, args=['-w'])704705Note that if you are using ``/`` as prefix character and you want to use a706boolean flag you need to separate it with ``;`` instead of ``/``:707708.. click:example::709710 @click.command()711 @click.option('/debug;/no-debug')712 def log(debug):713 click.echo('debug=%s' % debug)714715 if __name__ == '__main__':716 log()717718.. _ranges:719720Range Options721-------------722723A special mention should go to the :class:`IntRange` type, which works very724similarly to the :data:`INT` type, but restricts the value to fall into a725specific range (inclusive on both edges). It has two modes:726727- the default mode (non-clamping mode) where a value that falls outside728 of the range will cause an error.729- an optional clamping mode where a value that falls outside of the730 range will be clamped. This means that a range of ``0-5`` would731 return ``5`` for the value ``10`` or ``0`` for the value ``-1`` (for732 example).733734Example:735736.. click:example::737738 @click.command()739 @click.option('--count', type=click.IntRange(0, 20, clamp=True))740 @click.option('--digit', type=click.IntRange(0, 10))741 def repeat(count, digit):742 click.echo(str(digit) * count)743744 if __name__ == '__main__':745 repeat()746747And from the command line:748749.. click:run::750751 invoke(repeat, args=['--count=1000', '--digit=5'])752 invoke(repeat, args=['--count=1000', '--digit=12'])753754If you pass ``None`` for any of the edges, it means that the range is open755at that side.756757Callbacks for Validation758------------------------759760.. versionchanged:: 2.0761762If you want to apply custom validation logic, you can do this in the763parameter callbacks. These callbacks can both modify values as well as764raise errors if the validation does not work.765766In Click 1.0, you can only raise the :exc:`UsageError` but starting with767Click 2.0, you can also raise the :exc:`BadParameter` error, which has the768added advantage that it will automatically format the error message to769also contain the parameter name.770771Example:772773.. click:example::774775 def validate_rolls(ctx, param, value):776 try:777 rolls, dice = map(int, value.split('d', 2))778 return (dice, rolls)779 except ValueError:780 raise click.BadParameter('rolls need to be in format NdM')781782 @click.command()783 @click.option('--rolls', callback=validate_rolls, default='1d6')784 def roll(rolls):785 click.echo('Rolling a %d-sided dice %d time(s)' % rolls)786787 if __name__ == '__main__':788 roll()789790And what it looks like:791792.. click:run::793794 invoke(roll, args=['--rolls=42'])795 println()796 invoke(roll, args=['--rolls=2d12'])