advanced.rst
This file
Path
docs/advanced.rst
379 lines · 13.9 KiB
Last changed by
Fix typos in docs (#623)Radovan Bastbefore adoptionb5239af
History of this fileTake it
1Advanced Patterns2=================34.. currentmodule:: click56In addition to common functionality that is implemented in the library7itself, there are countless patterns that can be implemented by extending8Click. This page should give some insight into what can be accomplished.910.. _aliases:1112Command Aliases13---------------1415Many tools support aliases for commands. For instance, you can configure16``git`` to accept ``git ci`` as alias for ``git commit``. Other tools17also support auto-discovery for aliases by automatically shortening them.1819Click does not support this out of the box, but it's very easy to customize20the :class:`Group` or any other :class:`MultiCommand` to provide this21functionality.2223As explained in :ref:`custom-multi-commands`, a multi command can provide24two methods: :meth:`~MultiCommand.list_commands` and25:meth:`~MultiCommand.get_command`. In this particular case, you only need26to override the latter as you generally don't want to enumerate the27aliases on the help page in order to avoid confusion.2829This following example implements a subclass of :class:`Group` that30accepts 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):3233.. 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)))4849And it can then be used like this:5051.. 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 pass6465Parameter 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))118119120Token Normalization121-------------------122123.. versionadded:: 2.0124125Starting with Click 2.0, it's possible to provide a function that is used126for normalizing tokens. Tokens are option names, choice values, or command127values. This can be used to implement case insensitive options, for128instance.129130In 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:133134.. click:example::135136 CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower())137138 @click.command(context_settings=CONTEXT_SETTINGS)139 @click.option('--name', default='Pete')140 def cli(name):141 click.echo('Name: %s' % name)142143And how it works on the command line:144145.. click:run::146147 invoke(cli, prog_name='cli', args=['--NAME=Pete'])148149Invoking Other Commands150-----------------------151152Sometimes, it might be interesting to invoke one command from another153command. This is a pattern that is generally discouraged with Click, but154possible nonetheless. For this, you can use the :func:`Context.invoke`155or :func:`Context.forward` methods.156157They work similarly, but the difference is that :func:`Context.invoke` merely158invokes another command with the arguments you provide as a caller,159whereas :func:`Context.forward` fills in the arguments from the current160command. Both accept the command as the first argument and everything else161is passed onwards as you would expect.162163Example: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-------------------------192193Click works a bit differently than some other command line parsers in that194it attempts to reconcile the order of arguments as defined by the195programmer with the order of arguments as defined by the user before196invoking any callbacks.197198This is an important concept to understand when porting complex199patterns to Click from optparse or other systems. A parameter200callback invocation in optparse happens as part of the parsing step,201whereas a callback invocation in Click happens after the parsing.202203The main difference is that in optparse, callbacks are invoked with the raw204value as it happens, whereas a callback in Click is invoked after the205value has been fully converted.206207Generally, 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``.211212There are three exceptions to this rule which are important to know:213214Eagerness: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``220 and ``--version``. Both are eager parameters, but whatever parameter221 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 multiple225 places because it is repeated -- for instance, ``--exclude foo --include226 baz --exclude bar`` -- the callback will fire based on the position of227 the first option. In this case, the callback will fire for228 ``exclude`` and it will be passed both options (``foo`` and229 ``bar``), then the callback for ``include`` will fire with ``baz``230 only.231232 Note that even if a parameter does not allow multiple versions, Click233 will still accept the position of the first, but it will ignore every234 value except the last. The reason for this is to allow composability235 through shell aliases that set defaults.236237Missing parameters:238 If a parameter is not defined on the command line, the callback will239 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.243244Most 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.246247.. _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 recommended 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.341342343Global Context Access344---------------------345346.. versionadded:: 5.0347348Starting with Click 5.0 it is possible to access the current context from349anywhere within the same thread 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.