advanced.rst
This file
Path
docs/advanced.rst
379 lines · 13.9 KiB
Last changed by
Documented the use of get_current_contextArmin Ronacherbefore adoption421e46a
History of this fileTake it
The walk stopped after 200 commits: lines older than ae85be4 point at it.
Added notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
lines 1–6why, one step back1Advanced Patterns2=================34.. currentmodule:: click56In addition to common functionality that is implemented in the libraryMerge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd
line 7why, one step back7itself, there are countless patterns that can be implemented by extendingMerge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 8why, one step back8Click. This page should give some insight into what can be accomplished.Added notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
lines 9–14why, one step back910.. _aliases:1112Command Aliases13---------------14Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 15why, one step back15Many tools support aliases for commands. For instance, you can configureAdded notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
line 16why, one step back16``git`` to accept ``git ci`` as alias for ``git commit``. Other toolsMerge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd
line 17why, one step back17also support auto-discovery for aliases by automatically shortening them.Added notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
line 18why, one step back18Merge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd
line 19why, one step back19Click does not support this out of the box, but it's very easy to customizeAdded notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
lines 20–22why, one step back20the :class:`Group` or any other :class:`MultiCommand` to provide this21functionality.22Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 23why, one step back23As explained in :ref:`custom-multi-commands`, a multi command can provideAdded notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
line 24why, one step back24two methods: :meth:`~MultiCommand.list_commands` andDocumentation fixesKevin Yapbefore adoption67523af
line 25why, one step back25:meth:`~MultiCommand.get_command`. In this particular case, you only needAdded notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
line 26why, one step back26to override the latter as you generally don't want to enumerate theDocumentation fixesKevin Yapbefore adoption67523af
line 27why, one step back27aliases on the help page in order to avoid confusion.Added notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
lines 28–29why, one step back2829This following example implements a subclass of :class:`Group` thatMerge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd
lines 30–31why, one step back30accepts a prefix for a command. If there were a command called ``push``,31it would accept ``pus`` as an alias (so long as it was unique):Added notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
lines 32–48why, one step back3233.. click:example::3435 class AliasedGroup(click.Group):3637 def get_command(self, ctx, cmd_name):38 rv = click.Group.get_command(self, ctx, cmd_name)39 if rv is not None:40 return rv41 matches = [x for x in self.list_commands(ctx)42 if x.startswith(cmd_name)]43 if not matches:44 return None45 elif len(matches) == 1:46 return click.Group.get_command(self, ctx, matches[0])47 ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))48Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 49why, one step back49And it can then be used like this:Added notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
lines 50–64why, one step back5051.. click:example::5253 @click.command(cls=AliasedGroup)54 def cli():55 pass5657 @cli.command()58 def push():59 pass6061 @cli.command()62 def pop():63 pass64Added a chapter for parameter modificationsArmin Ronacherbefore adoptiona08cc28
lines 65–119why, one step back65Parameter Modifications66-----------------------6768Parameters (options and arguments) are forwarded to the command callbacks69as you have seen. One common way to prevent a parameter from being passed70to the callback is the `expose_value` argument to a parameter which hides71the parameter entirely. The way this works is that the :class:`Context`72object has a :attr:`~Context.params` attribute which is a dictionary of73all parameters. Whatever is in that dictionary is being passed to the74callbacks.7576This can be used to make up addition parameters. Generally this pattern77is not recommended but in some cases it can be useful. At the very least78it's good to know that the system works this way.7980.. click:example::8182 import urllib8384 def open_url(ctx, param, value):85 if value is not None:86 ctx.params['fp'] = urllib.urlopen(value)87 return value8889 @click.command()90 @click.option('--url', callback=open_url)91 def cli(url, fp=None):92 if fp is not None:93 click.echo('%s: %s' % (url, fp.code))9495In this case the callback returns the URL unchanged but also passes a96second ``fp`` value to the callback. What's more recommended is to pass97the information in a wrapper however:9899.. click:example::100101 import urllib102103 class URL(object):104105 def __init__(self, url, fp):106 self.url = url107 self.fp = fp108109 def open_url(ctx, param, value):110 if value is not None:111 return URL(value, urllib.urlopen(value))112113 @click.command()114 @click.option('--url', callback=open_url)115 def cli(url):116 if url is not None:117 click.echo('%s: %s' % (url.url, url.fp.code))118119Added example for token normalization.Armin Ronacherbefore adoption8da75f9
lines 120–124why, one step back120Token Normalization121-------------------122123.. versionadded:: 2.0124Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 125why, one step back125Starting with Click 2.0, it's possible to provide a function that is usedMerge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd
lines 126–127why, one step back126for normalizing tokens. Tokens are option names, choice values, or command127values. This can be used to implement case insensitive options, forAdded example for token normalization.Armin Ronacherbefore adoption8da75f9
lines 128–129why, one step back128instance.129Merge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd
lines 130–132why, one step back130In order to use this feature, the context needs to be passed a function that131performs the normalization of the token. For instance, you could have a132function that converts the token to lowercase:Added example for token normalization.Armin Ronacherbefore adoption8da75f9
lines 133–135why, one step back133134.. click:example::135defaults -> settingsArmin Ronacherbefore adoption1bc0a19
line 136why, one step back136 CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower())Added example for token normalization.Armin Ronacherbefore adoption8da75f9
line 137why, one step back137defaults -> settingsArmin Ronacherbefore adoption1bc0a19
line 138why, one step back138 @click.command(context_settings=CONTEXT_SETTINGS)Added example for token normalization.Armin Ronacherbefore adoption8da75f9
lines 139–142why, one step back139 @click.option('--name', default='Pete')140 def cli(name):141 click.echo('Name: %s' % name)142Merge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd
line 143why, one step back143And how it works on the command line:Added example for token normalization.Armin Ronacherbefore adoption8da75f9
lines 144–148why, one step back144145.. click:run::146147 invoke(cli, prog_name='cli', args=['--NAME=Pete'])148Added notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
lines 149–151why, one step back149Invoking Other Commands150-----------------------151Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 152why, one step back152Sometimes, it might be interesting to invoke one command from anotherMerge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 153why, one step back153command. This is a pattern that is generally discouraged with Click, butDocumentation fixesKevin Yapbefore adoption67523af
line 154why, one step back154possible nonetheless. For this, you can use the :func:`Context.invoke`Added notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
lines 155–156why, one step back155or :func:`Context.forward` methods.156Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 157why, one step back157They work similarly, but the difference is that :func:`Context.invoke` merelyAdded notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
lines 158–159why, one step back158invokes another command with the arguments you provide as a caller,159whereas :func:`Context.forward` fills in the arguments from the currentMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 160–161why, one step back160command. Both accept the command as the first argument and everything else161is passed onwards as you would expect.Added notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
lines 162–192why, one step back162163Example:164165.. click:example::166167 cli = click.Group()168169 @cli.command()170 @click.option('--count', default=1)171 def test(count):172 click.echo('Count: %d' % count)173174 @cli.command()175 @click.option('--count', default=1)176 @click.pass_context177 def dist(ctx, count):178 ctx.forward(test)179 ctx.invoke(test, count=42)180181And what it looks like:182183.. click:run::184185 invoke(cli, prog_name='cli', args=['dist'])186187188.. _callback-evaluation-order:189190Callback Evaluation Order191-------------------------192Documentation fixesKevin Yapbefore adoption67523af
line 193why, one step back193Click works a bit differently than some other command line parsers in thatAdded notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
lines 194–197why, one step back194it attempts to reconcile the order of arguments as defined by the195programmer with the order of arguments as defined by the user before196invoking any callbacks.197Documentation fixesKevin Yapbefore adoption67523af
line 198why, one step back198This is an important concept to understand when porting complexMerge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 199why, one step back199patterns to Click from optparse or other systems. A parameterDocumentation fixesKevin Yapbefore adoption67523af
line 200why, one step back200callback invocation in optparse happens as part of the parsing step,Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 201why, one step back201whereas a callback invocation in Click happens after the parsing.Added notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
line 202why, one step back202Documentation fixesKevin Yapbefore adoption67523af
line 203why, one step back203The main difference is that in optparse, callbacks are invoked with the rawMerge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 204why, one step back204value as it happens, whereas a callback in Click is invoked after theAdded notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
lines 205–206why, one step back205value has been fully converted.206Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 207–210why, one step back207Generally, the order of invocation is driven by the order in which the user208provides the arguments to the script; if there is an option called ``--foo``209and an option called ``--bar`` and the user calls it as ``--bar210--foo``, then the callback for ``bar`` will fire before the one for ``foo``.Added notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
line 211why, one step back211two -> threeArmin Ronacherbefore adoption6251839
line 212why, one step back212There are three exceptions to this rule which are important to know:Added notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
lines 213–219why, one step back213214Eagerness:215 An option can be set to be "eager". All eager parameters are216 evaluated before all non-eager parameters, but again in the order as217 they were provided on the command line by the user.218219 This is important for parameters that execute and exit like ``--help``Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 220why, one step back220 and ``--version``. Both are eager parameters, but whatever parameterAdded notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
lines 221–224why, one step back221 comes first on the command line will win and exit the program.222223Repeated parameters:224 If an option or argument is split up on the command line into multipleDocumentation fixesKevin Yapbefore adoption67523af
lines 225–226why, one step back225 places because it is repeated -- for instance, ``--exclude foo --include226 baz --exclude bar`` -- the callback will fire based on the position ofMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 227why, one step back227 the first option. In this case, the callback will fire forAdded notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
lines 228–231why, one step back228 ``exclude`` and it will be passed both options (``foo`` and229 ``bar``), then the callback for ``include`` will fire with ``baz``230 only.231Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 232why, one step back232 Note that even if a parameter does not allow multiple versions, ClickAdded notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
line 233why, one step back233 will still accept the position of the first, but it will ignore everyfirst -> lastArmin Ronacherbefore adoption80e15d5
line 234why, one step back234 value except the last. The reason for this is to allow composabilityAdded notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
lines 235–237why, one step back235 through shell aliases that set defaults.236237Missing parameters:Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 238why, one step back238 If a parameter is not defined on the command line, the callback willAdded notes on keyboard interruptsArmin Ronacherbefore adoptionae85be4
lines 239–243why, one step back239 still fire. This is different from how it works in optparse where240 undefined values do not fire the callback. Missing parameters fire241 their callbacks at the very end which makes it possible for them to242 default to values from a parameter that came before.243Documentation fixesKevin Yapbefore adoption67523af
lines 244–245why, one step back244Most of the time you do not need to be concerned about any of this,245but it is important to know how it works for some advanced cases.Added example on ignoring of unknown options.Armin Ronacherbefore adoption4851f7c
lines 246–340why, one step back246247.. _forwarding-unknown-options:248249Forwarding Unknown Options250--------------------------251252In some situations it is interesting to be able to accept all unknown253options for further manual processing. Click can generally do that as of254Click 4.0, but it has some limitations that lie in the nature of the255problem. The support for this is provided through a parser flag called256``ignore_unknown_options`` which will instruct the parser to collect all257unknown options and to put them to the leftover argument instead of258triggering a parsing error.259260This can generally be activated in two different ways:2612621. It can be enabled on custom :class:`Command` subclasses by changing263 the :attr:`~BaseCommand.ignore_unknown_options` attribute.2642. It can be enabled by changing the attribute of the same name on the265 context class (:attr:`Context.ignore_unknown_options`). This is best266 changed through the ``context_settings`` dictionary on the command.267268For most situations the easiest solution is the second. Once the behavior269is changed something needs to pick up those leftover options (which at270this point are considered arguments). For this again you have two271options:2722731. You can use :func:`pass_context` to get the context passed. This will274 only work if in addition to :attr:`~Context.ignore_unknown_options`275 you also set :attr:`~Context.allow_extra_args` as otherwise the276 command will abort with an error that there are leftover arguments.277 If you go with this solution, the extra arguments will be collected in278 :attr:`Context.args`.2792. You can attach a :func:`argument` with ``nargs`` set to `-1` which280 will eat up all leftover arguments. In this case it's recommeded to281 set the `type` to :data:`UNPROCESSED` to avoid any string processing282 on those arguments as otherwise they are forced into unicode strings283 automatically which is often not what you want.284285In the end you end up with something like this:286287.. click:example::288289 import sys290 from subprocess import call291292 @click.command(context_settings=dict(293 ignore_unknown_options=True,294 ))295 @click.option('-v', '--verbose', is_flag=True, help='Enables verbose mode')296 @click.argument('timeit_args', nargs=-1, type=click.UNPROCESSED)297 def cli(verbose, timeit_args):298 """A wrapper around Python's timeit."""299 cmdline = ['python', '-mtimeit'] + list(timeit_args)300 if verbose:301 click.echo('Invoking: %s' % ' '.join(cmdline))302 call(cmdline)303304And what it looks like:305306.. click:run::307308 invoke(cli, prog_name='cli', args=['--help'])309 println()310 invoke(cli, prog_name='cli', args=['-n', '100', 'a = 1; b = 2; a * b'])311 println()312 invoke(cli, prog_name='cli', args=['-v', 'a = 1; b = 2; a * b'])313314As you can see the verbosity flag is handled by Click, everything else315ends up in the `timeit_args` variable for further processing which then316for instance, allows invoking a subprocess. There are a few things that317are important to know about how this ignoring of unhandled flag happens:318319* Unknown long options are generally ignored and not processed at all.320 So for instance if ``--foo=bar`` or ``--foo bar`` are passed they321 generally end up like that. Note that because the parser cannot know322 if an option will accept an argument or not, the ``bar`` part might be323 handled as an argument.324* Unknown short options might be partially handled and reassmebled if325 necessary. For instance in the above example there is an option326 called ``-v`` which enables verbose mode. If the command would be327 ignored with ``-va`` then the ``-v`` part would be handled by Click328 (as it is known) and ``-a`` would end up in the leftover parameters329 for further processing.330* Depending on what you plan on doing you might have some success by331 disabling interspersed arguments332 (:attr:`~Context.allow_interspersed_args`) which instructs the parser333 to not allow arguments and options to be mixed. Depending on your334 situation this might improve your results.335336Generally though the combinated handling of options and arguments from337your own commands and commands from another application are discouraged338and if you can avoid it, you should. It's a much better idea to have339everything below a subcommand be forwarded to another application than to340handle some arguments yourself.Documented the use of get_current_contextArmin Ronacherbefore adoption421e46a
lines 341–379why, one step back341342343Global Context Access344---------------------345346.. versionadded:: 5.0347348Starting with Click 5.0 it is possible to access the current context from349anywhere within the same through through the use of the350:func:`get_current_context` function which returns it. This is primarily351useful for accessing the context bound object as well as some flags that352are stored on it to customize the runtime behavior. For instance the353:func:`echo` function does this to infer the default value of the `color`354flag.355356Example usage::357358 def get_current_command_name():359 return click.get_current_context().info_name360361It should be noted that this only works within the current thread. If you362spawn additional threads then those threads will not have the ability to363refer to the current context. If you want to give another thread the364ability to refer to this context you need to use the context within the365thread as a context manager::366367 def spawn_thread(ctx, func):368 def wrapper():369 with ctx:370 func()371 t = threading.Thread(target=wrapper)372 t.start()373 return t374375Now the thread function can access the context like the main thread would376do. However if you do use this for threading you need to be very careful377as the vast majority of the context is not thread safe! You are only378allowed to read from the context, but not to perform any modifications on379it.