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
The walk stopped after 200 commits: lines older than 469ba25 point at it.
Merge branch 'master' of https://github.com/mitsuhiko/clickArmin Ronacherbefore adoption4ee540d
lines 1–2why, one step back1.. _options:2Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 3–8why, one step back3Options4=======56.. currentmodule:: click78Adding options to commands can be accomplished by the :func:`option`Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 9why, one step back9decorator. Since options can come in various different versions, thereMerge branch 'master' of https://github.com/mitsuhiko/clickArmin Ronacherbefore adoption4ee540d
lines 10–11why, one step back10are a ton of parameters to configure their behavior. Options in click are11distinct from :ref:`positional arguments <arguments>`.Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 12–16why, one step back1213Basic Value Options14-------------------1516The most basic option is a value option. These options accept oneMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 17why, one step back17argument which is a value. If no type is provided, the type of the defaultDocumentation fixesKevin Yapbefore adoption67523af
line 18why, one step back18value is used. If no default value is provided, the type is assumed to beMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 19–20why, one step back19:data:`STRING`. By default, the name of the parameter is the first long20option defined; otherwise the first short one is used.Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 21–40why, one step back2122.. 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-------------------40Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 41why, one step back41Sometimes, you have options that take more than one argument. For options,Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 42–60why, one step back42only 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----------------60Documentation fixesKevin Yapbefore adoption67523af
lines 61–65why, one step back61Similarly 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:Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 66–84why, one step back6667Example: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--------84Documentation fixesKevin Yapbefore adoption67523af
line 85why, one step back85In some very rare circumstances, it is interesting to use the repetitionMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 86–87why, one step back86of options to count an integer up. This can be used for verbosity flags,87for instance:Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 88–106why, one step back8889.. 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 (``/``)Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 107why, one step back107for enabling or disabling the option. (If a slash is in an option string,Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 108why, one step back108Click automatically knows that it's a boolean flag and will passMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 109why, one step back109``is_flag=True`` implicitly.) Click always wants you to provide an enableImplemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 110–132why, one step back110and 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'])132Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 133why, one step back133If you really don't want an off-switch, you can just define one andMerge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 134why, one step back134manually inform Click that something is a flag:Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 135–153why, one step back135136.. 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'])153Documentation fixesKevin Yapbefore adoption67523af
lines 154–156why, one step back154Note 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:Improved handling of dos/windows arguments greatly.Armin Ronacherbefore adoption133c417
lines 157–167why, one step back157158.. 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()167Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 168–170why, one step back168Feature Switches169----------------170Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 171–173why, one step back171In 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,Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 174why, one step back174Click will implicitly set ``is_flag=True``.Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25
line 175why, one step back175Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 176why, one step back176To set a default flag, assign a value of `True` to the flag that should beImplemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 177–202why, one step back177the 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--------------202Documentation fixesKevin Yapbefore adoption67523af
line 203why, one step back203Sometimes, you want to have a parameter be a choice of a list of values.Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 204–230why, one step back204In 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---------230Documentation fixesKevin Yapbefore adoption67523af
lines 231–232why, one step back231In 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 withMerge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 233why, one step back233Click by defining a prompt string.Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 234–250why, one step back234235Example: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'])250Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 251why, one step back251If you are not happy with the default prompt string, you can ask forImplemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 252–286why, one step back252a 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'])286Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 287why, one step back287Because this combination of parameters is quite common, this can also beImplemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 288–299why, one step back288replaced 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---------------------------299Documentation fixesKevin Yapbefore adoption67523af
line 300why, one step back300Sometimes, you want a parameter to completely change the execution flow.Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 301why, one step back301For instance, this is the case when you want to have a ``--version``Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 302–303why, one step back302parameter that prints out the version and then exits the application.303Documentation fixesKevin Yapbefore adoption67523af
lines 304–305why, one step back304In such cases, you need two concepts: eager parameters and a callback. An305eager parameter is a parameter that is handled before others, and aImplemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 306–307why, one step back306callback is what executes after the parameter is handled. The eagerness307is necessary so that an earlier required parameter does not produce anDocumentation fixesKevin Yapbefore adoption67523af
line 308why, one step back308error message. For instance, if ``--version`` was not eager and aImplemented atomic file opening support.Armin Ronacherbefore adoption469ba25
line 309why, one step back309parameter ``--foo`` was required and defined before, you would need toDocumentation fixesKevin Yapbefore adoption67523af
line 310why, one step back310specify it for ``--version`` to work. For more information, seeImplemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 311–321why, one step back311: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::321Changed parameter callback signature.Armin Ronacherbefore adoptionbda39db
line 322why, one step back322 def print_version(ctx, param, value):Added resilient parsing to the docsArmin Ronacherbefore adoptionaeb297c
line 323why, one step back323 if not value or ctx.resilient_parsing:Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 324–333why, one step back324 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!')333Documentation fixesKevin Yapbefore adoption67523af
lines 334–335why, one step back334The `expose_value` parameter prevents the pretty pointless ``version``335parameter from being passed to the callback. If that was not specified, aAdded resilient parsing to the docsArmin Ronacherbefore adoptionaeb297c
line 336why, one step back336boolean would be passed to the `hello` script. The `resilient_parsing`Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 337why, one step back337flag is applied to the context if Click wants to parse the command lineMerge branch 'master' of https://github.com/mitsuhiko/clickArmin Ronacherbefore adoptiona489e0e
line 338why, one step back338without any destructive behavior that would change the execution flow. InMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 339why, one step back339this case, because we would exit the program, we instead do nothing.Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 340–347why, one step back340341What it looks like:342343.. click:run::344345 invoke(hello)346 invoke(hello, args=['--version'])347Added notes on callback changes to the docsArmin Ronacherbefore adoptiond27f3a6
lines 348–349why, one step back348.. admonition:: Callback Signature Changes349Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 350why, one step back350 In Click 2.0 the signature for callbacks changed. For moreAdded notes on callback changes to the docsArmin Ronacherbefore adoptiond27f3a6
lines 351–352why, one step back351 information about these changes see :ref:`upgrade-to-2.0`.352Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 353–355why, one step back353Yes Parameters354--------------355Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 356why, one step back356For dangerous operations, it's very useful to be able to ask a user forImplemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 357–362why, one step back357confirmation. 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::362Changed parameter callback signature.Armin Ronacherbefore adoptionbda39db
line 363why, one step back363 def abort_if_false(ctx, param, value):Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 364–380why, one step back364 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'])380Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 381why, one step back381Because this combination of parameters is quite common, this can also beImplemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 382–389why, one step back382replaced 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!')Added notes on callback changes to the docsArmin Ronacherbefore adoptiond27f3a6
lines 390–392why, one step back390391.. admonition:: Callback Signature Changes392Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 393why, one step back393 In Click 2.0 the signature for callbacks changed. For moreAdded notes on callback changes to the docsArmin Ronacherbefore adoptiond27f3a6
line 394why, one step back394 information about these changes see :ref:`upgrade-to-2.0`.Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 395–398why, one step back395396Values from Environment Variables397---------------------------------398Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 399why, one step back399A very useful feature of Click is the ability to accept parameters fromImplemented atomic file opening support.Armin Ronacherbefore adoption469ba25
line 400why, one step back400environment variables in addition to regular parameters. This allowsMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 401–403why, one step back401tools 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 developmentImplemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 404–405why, one step back404experience.405Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 406why, one step back406This is supported by Click in two ways. One is to automatically buildImplemented atomic file opening support.Armin Ronacherbefore adoption469ba25
line 407why, one step back407environment variables which is supported for options only. To enable thisMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 408–410why, one step back408feature, 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 subcommandImplemented atomic file opening support.Armin Ronacherbefore adoption469ba25
line 411why, one step back411called ``foo`` taking an option called ``bar`` and the prefix isMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 412why, one step back412``MY_TOOL``, then the variable is ``MY_TOOL_FOO_BAR``.Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 413–461why, one step back413414Example 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 wayMerge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 462why, one step back462Click solves this is by leaving it up to the type to customize thisImplemented atomic file opening support.Armin Ronacherbefore adoption469ba25
line 463why, one step back463behavior. For both ``multiple`` and ``nargs`` with values other thanMerge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 464why, one step back464``1``, Click will invoke the :meth:`ParamType.split_envvar_value` method toImplemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 465–469why, one step back465perform 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.Merge pull request #113 from iKevinY/doc-fixesArmin Ronacherbefore adoptione0ea94a
line 470why, one step back470On Unix systems like Linux and OS X, the splitting happens for those onMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 471why, one step back471every colon (``:``), and for Windows, on every semicolon (``;``).Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 472–496why, one step back472473Example 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-----------------------496Documentation fixesKevin Yapbefore adoption67523af
line 497why, one step back497Click can deal with alternative prefix characters other than ``-`` forImplemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 498–499why, one step back498options. This is for instance useful if you want to handle slashes as499parameters ``/`` or something similar. Note that this is stronglyMerge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 500why, one step back500discouraged in general because Click wants developers to stay close toImplemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 501–518why, one step back501POSIX 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'])Improved handling of dos/windows arguments greatly.Armin Ronacherbefore adoption133c417
lines 519–531why, one step back519520Note 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()Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 532–537why, one step back532533.. _ranges:534535Range Options536-------------537Documentation fixesKevin Yapbefore adoption67523af
lines 538–539why, one step back538A special mention should go to the :class:`IntRange` type, which works very539similarly to the :data:`INT` type, but restricts the value to fall into aImplemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 540–541why, one step back540specific range (inclusive on both edges). It has two modes:541Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 542why, one step back542- the default mode (non-clamping mode) where a value that falls outsideImplemented atomic file opening support.Armin Ronacherbefore adoption469ba25
lines 543–568why, one step back543 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'])568Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 569why, one step back569If you pass ``None`` for any of the edges, it means that the range is openImplemented atomic file opening support.Armin Ronacherbefore adoption469ba25
line 570why, one step back570at that side.Added validation to docsArmin Ronacherbefore adoptiondf8f00b
lines 571–576why, one step back571572Callbacks for Validation573------------------------574575.. versionchanged:: 2.0576Documentation fixesKevin Yapbefore adoption67523af
line 577why, one step back577If you want to apply custom validation logic, you can do this in theAdded validation to docsArmin Ronacherbefore adoptiondf8f00b
lines 578–580why, one step back578parameter callbacks. These callbacks can both modify values as well as579raise errors if the validation does not work.580Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
lines 581–582why, one step back581In 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 theAdded validation to docsArmin Ronacherbefore adoptiondf8f00b
lines 583–589why, one step back583added advantage that it will automatically format the error message to584also contain the parameter name.585586Example:587588.. click:example::589Changed parameter callback signature.Armin Ronacherbefore adoptionbda39db
line 590why, one step back590 def validate_rolls(ctx, param, value):Added validation to docsArmin Ronacherbefore adoptiondf8f00b
lines 591–611why, one step back591 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'])