options.rst
This file
Path
docs/options.rst
611 lines · 16.6 KiB
Last changed by
Merge branch 'master' of https://github.com/mitsuhiko/clickArmin Ronacherbefore adoption4ee540d
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'])5758Multiple Options59----------------6061Similarly to ``nargs``, there is also the case of wanting to support a62parameter being provided multiple times to and have all values recorded --63not just the last one. For instance, ``git commit -m foo -m bar`` would64record two lines for the commit message: ``foo`` and ``bar``. This can be65accomplished with the ``multiple`` flag:6667Example:6869.. click:example::7071 @click.command()72 @click.option('--message', '-m', multiple=True)73 def commit(message):74 click.echo('\n'.join(message))7576And on the command line:7778.. click:run::7980 invoke(commit, args=['-m', 'foo', '-m', 'bar'])8182Counting83--------8485In some very rare circumstances, it is interesting to use the repetition86of options to count an integer up. This can be used for verbosity flags,87for instance:8889.. click:example::9091 @click.command()92 @click.option('-v', '--verbose', count=True)93 def log(verbose):94 click.echo('Verbosity: %s' % verbose)9596And on the command line:9798.. click:run::99100 invoke(log, args=['-vvv'])101102Boolean Flags103-------------104105Boolean flags are options that can be enabled or disabled. This can be106accomplished by defining two flags in one go separated by a slash (``/``)107for enabling or disabling the option. (If a slash is in an option string,108Click automatically knows that it's a boolean flag and will pass109``is_flag=True`` implicitly.) Click always wants you to provide an enable110and disable flag so that you can change the default later.111112Example:113114.. click:example::115116 import os117118 @click.command()119 @click.option('--shout/--no-shout', default=False)120 def info(shout):121 rv = os.uname()[0]122 if shout:123 rv = rv.upper() + '!!!!111'124 click.echo(rv)125126And on the command line:127128.. click:run::129130 invoke(info, args=['--shout'])131 invoke(info, args=['--no-shout'])132133If you really don't want an off-switch, you can just define one and134manually inform Click that something is a flag:135136.. click:example::137138 import os139140 @click.command()141 @click.option('--shout', is_flag=True)142 def info(shout):143 rv = os.uname()[0]144 if shout:145 rv = rv.upper() + '!!!!111'146 click.echo(rv)147148And on the command line:149150.. click:run::151152 invoke(info, args=['--shout'])153154Note that if a slash is contained in your option already (for instance, if155you use Windows-style parameters where ``/`` is the prefix character), you156can alternatively split the parameters through ``;`` instead:157158.. click:example::159160 @click.command()161 @click.option('/debug;/no-debug')162 def log(debug):163 click.echo('debug=%s' % debug)164165 if __name__ == '__main__':166 log()167168Feature Switches169----------------170171In addition to boolean flags, there are also feature switches. These are172implemented by setting multiple options to the same parameter name and173defining a flag value. Note that by providing the ``flag_value`` parameter,174Click will implicitly set ``is_flag=True``.175176To set a default flag, assign a value of `True` to the flag that should be177the default.178179.. click:example::180181 import os182183 @click.command()184 @click.option('--upper', 'transformation', flag_value='upper',185 default=True)186 @click.option('--lower', 'transformation', flag_value='lower')187 def info(transformation):188 click.echo(getattr(os.uname()[0], transformation)())189190And on the command line:191192.. click:run::193194 invoke(info, args=['--upper'])195 invoke(info, args=['--lower'])196 invoke(info)197198.. _choice-opts:199200Choice Options201--------------202203Sometimes, you want to have a parameter be a choice of a list of values.204In that case you can use :class:`Choice` type. It can be instantiated205with a list of valid values.206207Example:208209.. click:example::210211 @click.command()212 @click.option('--hash-type', type=click.Choice(['md5', 'sha1']))213 def digest(hash_type):214 click.echo(hash_type)215216What it looks like:217218.. click:run::219220 invoke(digest, args=['--hash-type=md5'])221 println()222 invoke(digest, args=['--hash-type=foo'])223 println()224 invoke(digest, args=['--help'])225226.. _option-prompting:227228Prompting229---------230231In some cases, you want parameters that can be provided from the command line,232but if not provided, ask for user input instead. This can be implemented with233Click by defining a prompt string.234235Example:236237.. click:example::238239 @click.command()240 @click.option('--name', prompt=True)241 def hello(name):242 click.echo('Hello %s!' % name)243244And what it looks like:245246.. click:run::247248 invoke(hello, args=['--name=John'])249 invoke(hello, input=['John'])250251If you are not happy with the default prompt string, you can ask for252a different one:253254.. click:example::255256 @click.command()257 @click.option('--name', prompt='Your name please')258 def hello(name):259 click.echo('Hello %s!' % name)260261What it looks like:262263.. click:run::264265 invoke(hello, input=['John'])266267Password Prompts268----------------269270Click also supports hidden prompts and asking for confirmation. This is271useful for password input:272273.. click:example::274275 @click.command()276 @click.option('--password', prompt=True, hide_input=True,277 confirmation_prompt=True)278 def encrypt(password):279 click.echo('Encrypting password to %s' % password.encode('rot13'))280281What it looks like:282283.. click:run::284285 invoke(encrypt, input=['secret', 'secret'])286287Because this combination of parameters is quite common, this can also be288replaced with the :func:`password_option` decorator:289290.. click:example::291292 @click.command()293 @click.password_option()294 def encrypt(password):295 click.echo('Encrypting password to %s' % password.encode('rot13'))296297Callbacks and Eager Options298---------------------------299300Sometimes, you want a parameter to completely change the execution flow.301For instance, this is the case when you want to have a ``--version``302parameter that prints out the version and then exits the application.303304In such cases, you need two concepts: eager parameters and a callback. An305eager parameter is a parameter that is handled before others, and a306callback is what executes after the parameter is handled. The eagerness307is necessary so that an earlier required parameter does not produce an308error message. For instance, if ``--version`` was not eager and a309parameter ``--foo`` was required and defined before, you would need to310specify it for ``--version`` to work. For more information, see311:ref:`callback-evaluation-order`.312313A callback is a function that is invoked with two parameters: the current314:class:`Context` and the value. The context provides some useful features315such as quitting the application and gives access to other already316processed parameters.317318Here an example for a ``--version`` flag:319320.. click:example::321322 def print_version(ctx, param, value):323 if not value or ctx.resilient_parsing:324 return325 click.echo('Version 1.0')326 ctx.exit()327328 @click.command()329 @click.option('--version', is_flag=True, callback=print_version,330 expose_value=False, is_eager=True)331 def hello():332 click.echo('Hello World!')333334The `expose_value` parameter prevents the pretty pointless ``version``335parameter from being passed to the callback. If that was not specified, a336boolean would be passed to the `hello` script. The `resilient_parsing`337flag is applied to the context if Click wants to parse the command line338without any destructive behavior that would change the execution flow. In339this case, because we would exit the program, we instead do nothing.340341What it looks like:342343.. click:run::344345 invoke(hello)346 invoke(hello, args=['--version'])347348.. admonition:: Callback Signature Changes349350 In Click 2.0 the signature for callbacks changed. For more351 information about these changes see :ref:`upgrade-to-2.0`.352353Yes Parameters354--------------355356For dangerous operations, it's very useful to be able to ask a user for357confirmation. This can be done by adding a boolean ``--yes`` flag and358asking for confirmation if the user did not provide it and to fail in a359callback:360361.. click:example::362363 def abort_if_false(ctx, param, value):364 if not value:365 ctx.abort()366367 @click.command()368 @click.option('--yes', is_flag=True, callback=abort_if_false,369 expose_value=False,370 prompt='Are you sure you want to drop the db?')371 def dropdb():372 click.echo('Dropped all tables!')373374And what it looks like on the command line:375376.. click:run::377378 invoke(dropdb, input=['n'])379 invoke(dropdb, args=['--yes'])380381Because this combination of parameters is quite common, this can also be382replaced with the :func:`confirmation_option` decorator:383384.. click:example::385386 @click.command()387 @click.confirmation_option(help='Are you sure you want to drop the db?')388 def dropdb():389 click.echo('Dropped all tables!')390391.. admonition:: Callback Signature Changes392393 In Click 2.0 the signature for callbacks changed. For more394 information about these changes see :ref:`upgrade-to-2.0`.395396Values from Environment Variables397---------------------------------398399A very useful feature of Click is the ability to accept parameters from400environment variables in addition to regular parameters. This allows401tools to be automated much easier. For instance, you might want to pass402a configuration file with a ``--config`` parameter but also support exporting403a ``TOOL_CONFIG=hello.cfg`` key-value pair for a nicer development404experience.405406This is supported by Click in two ways. One is to automatically build407environment variables which is supported for options only. To enable this408feature, the ``auto_envvar_prefix`` parameter needs to be passed to the409script that is invoked. Each command and parameter is then added as an410uppercase underscore-separated variable. If you have a subcommand411called ``foo`` taking an option called ``bar`` and the prefix is412``MY_TOOL``, then the variable is ``MY_TOOL_FOO_BAR``.413414Example usage:415416.. click:example::417418 @click.command()419 @click.option('--username')420 def greet(username):421 click.echo('Hello %s!' % username)422423 if __name__ == '__main__':424 greet(auto_envvar_prefix='GREETER')425426And from the command line:427428.. click:run::429430 invoke(greet, env={'GREETER_USERNAME': 'john'},431 auto_envvar_prefix='GREETER')432433The second option is to manually pull values in from specific environment434variables by defining the name of the environment variable on the option.435436Example usage:437438.. click:example::439440 @click.command()441 @click.option('--username', envvar='USERNAME')442 def greet(username):443 click.echo('Hello %s!' % username)444445 if __name__ == '__main__':446 greet()447448And from the command line:449450.. click:run::451452 invoke(greet, env={'USERNAME': 'john'})453454In that case it can also be a list of different environment variables455where the first one is picked.456457Multiple Values from Environment Values458---------------------------------------459460As options can accept multiple values, pulling in such values from461environment variables (which are strings) is a bit more complex. The way462Click solves this is by leaving it up to the type to customize this463behavior. For both ``multiple`` and ``nargs`` with values other than464``1``, Click will invoke the :meth:`ParamType.split_envvar_value` method to465perform the splitting.466467The default implementation for all types is to split on whitespace. The468exceptions to this rule are the :class:`File` and :class:`Path` types469which both split according to the operating system's path splitting rules.470On Unix systems like Linux and OS X, the splitting happens for those on471every colon (``:``), and for Windows, on every semicolon (``;``).472473Example usage:474475.. click:example::476477 @click.command()478 @click.option('paths', '--path', envvar='PATHS', multiple=True,479 type=click.Path())480 def perform(paths):481 for path in paths:482 click.echo(path)483484 if __name__ == '__main__':485 perform()486487And from the command line:488489.. click:run::490491 import os492 invoke(perform, env={'PATHS': './foo/bar%s./test' % os.path.pathsep})493494Other Prefix Characters495-----------------------496497Click can deal with alternative prefix characters other than ``-`` for498options. This is for instance useful if you want to handle slashes as499parameters ``/`` or something similar. Note that this is strongly500discouraged in general because Click wants developers to stay close to501POSIX semantics. However in certain situations this can be useful:502503.. click:example::504505 @click.command()506 @click.option('+w/-w')507 def chmod(w):508 click.echo('writable=%s' % w)509510 if __name__ == '__main__':511 chmod()512513And from the command line:514515.. click:run::516517 invoke(chmod, args=['+w'])518 invoke(chmod, args=['-w'])519520Note that if you are using ``/`` as prefix character and you want to use a521boolean flag you need to separate it with ``;`` instead of ``/``:522523.. click:example::524525 @click.command()526 @click.option('/debug;/no-debug')527 def log(debug):528 click.echo('debug=%s' % debug)529530 if __name__ == '__main__':531 log()532533.. _ranges:534535Range Options536-------------537538A special mention should go to the :class:`IntRange` type, which works very539similarly to the :data:`INT` type, but restricts the value to fall into a540specific range (inclusive on both edges). It has two modes:541542- the default mode (non-clamping mode) where a value that falls outside543 of the range will cause an error.544- an optional clamping mode where a value that falls outside of the545 range will be clamped. This means that a range of ``0-5`` would546 return ``5`` for the value ``10`` or ``0`` for the value ``-1`` (for547 example).548549Example:550551.. click:example::552553 @click.command()554 @click.option('--count', type=click.IntRange(0, 20, clamp=True))555 @click.option('--digit', type=click.IntRange(0, 10))556 def repeat(count, digit):557 click.echo(str(digit) * count)558559 if __name__ == '__main__':560 repeat()561562And from the command line:563564.. click:run::565566 invoke(repeat, args=['--count=1000', '--digit=5'])567 invoke(repeat, args=['--count=1000', '--digit=12'])568569If you pass ``None`` for any of the edges, it means that the range is open570at that side.571572Callbacks for Validation573------------------------574575.. versionchanged:: 2.0576577If you want to apply custom validation logic, you can do this in the578parameter callbacks. These callbacks can both modify values as well as579raise errors if the validation does not work.580581In Click 1.0, you can only raise the :exc:`UsageError` but starting with582Click 2.0, you can also raise the :exc:`BadParameter` error, which has the583added advantage that it will automatically format the error message to584also contain the parameter name.585586Example:587588.. click:example::589590 def validate_rolls(ctx, param, value):591 try:592 rolls, dice = map(int, value.split('d', 2))593 return (dice, rolls)594 except ValueError:595 raise click.BadParameter('rolls need to be in format NdM')596597 @click.command()598 @click.option('--rolls', callback=validate_rolls, default='1d6')599 def roll(rolls):600 click.echo('Rolling a %d-sided dice %d time(s)' % rolls)601602 if __name__ == '__main__':603 roll()604605And what it looks like:606607.. click:run::608609 invoke(roll, args=['--rolls=42'])610 println()611 invoke(roll, args=['--rolls=2d12'])