Skip to content
Myr

advanced.rst

This file

Path

docs/advanced.rst

245 lines · 8.2 KiB

Last changed by

first -> lastArmin Ronacherbefore adoption80e15d5

History of this file

Take 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.