Skip to content
Myr

advanced.rst

This file

Path

docs/advanced.rst

190 lines · 6.6 KiB

Last changed by

Merge pull request #125 from iKevinY/doc-fixesArmin Ronacherbefore adoption1d25afd

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        pass6465Token Normalization66-------------------6768.. versionadded:: 2.06970Starting with click 2.0, it's possible to provide a function that is used71for normalizing tokens.  Tokens are option names, choice values, or command72values.  This can be used to implement case insensitive options, for73instance.7475In order to use this feature, the context needs to be passed a function that76performs the normalization of the token.  For instance, you could have a77function that converts the token to lowercase:7879.. click:example::8081    CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower())8283    @click.command(context_settings=CONTEXT_SETTINGS)84    @click.option('--name', default='Pete')85    def cli(name):86        click.echo('Name: %s' % name)8788And how it works on the command line:8990.. click:run::9192    invoke(cli, prog_name='cli', args=['--NAME=Pete'])9394Invoking Other Commands95-----------------------9697Sometimes, it might be interesting to invoke one command from another98command.  This is a pattern that is generally discouraged with click, but99possible nonetheless.  For this, you can use the :func:`Context.invoke`100or :func:`Context.forward` methods.101102They work similarly, but the difference is that :func:`Context.invoke` merely103invokes another command with the arguments you provide as a caller,104whereas :func:`Context.forward` fills in the arguments from the current105command.  Both accept the command as the first argument and everything else106is passed onwards as you would expect.107108Example:109110.. click:example::111112    cli = click.Group()113114    @cli.command()115    @click.option('--count', default=1)116    def test(count):117        click.echo('Count: %d' % count)118119    @cli.command()120    @click.option('--count', default=1)121    @click.pass_context122    def dist(ctx, count):123        ctx.forward(test)124        ctx.invoke(test, count=42)125126And what it looks like:127128.. click:run::129130    invoke(cli, prog_name='cli', args=['dist'])131132133.. _callback-evaluation-order:134135Callback Evaluation Order136-------------------------137138Click works a bit differently than some other command line parsers in that139it attempts to reconcile the order of arguments as defined by the140programmer with the order of arguments as defined by the user before141invoking any callbacks.142143This is an important concept to understand when porting complex144patterns to click from optparse or other systems.  A parameter145callback invocation in optparse happens as part of the parsing step,146whereas a callback invocation in click happens after the parsing.147148The main difference is that in optparse, callbacks are invoked with the raw149value as it happens, whereas a callback in click is invoked after the150value has been fully converted.151152Generally, the order of invocation is driven by the order in which the user153provides the arguments to the script; if there is an option called ``--foo``154and an option called ``--bar`` and the user calls it as ``--bar155--foo``, then the callback for ``bar`` will fire before the one for ``foo``.156157There are two exceptions to this rule which are important to know:158159Eagerness:160    An option can be set to be "eager".  All eager parameters are161    evaluated before all non-eager parameters, but again in the order as162    they were provided on the command line by the user.163164    This is important for parameters that execute and exit like ``--help``165    and ``--version``.  Both are eager parameters, but whatever parameter166    comes first on the command line will win and exit the program.167168Repeated parameters:169    If an option or argument is split up on the command line into multiple170    places because it is repeated -- for instance, ``--exclude foo --include171    baz --exclude bar`` -- the callback will fire based on the position of172    the first option.  In this case, the callback will fire for173    ``exclude`` and it will be passed both options (``foo`` and174    ``bar``), then the callback for ``include`` will fire with ``baz``175    only.176177    Note that even if a parameter does not allow multiple versions, click178    will still accept the position of the first, but it will ignore every179    value except the first.  The reason for this is to allow composability180    through shell aliases that set defaults.181182Missing parameters:183    If a parameter is not defined on the command line, the callback will184    still fire.  This is different from how it works in optparse where185    undefined values do not fire the callback.  Missing parameters fire186    their callbacks at the very end which makes it possible for them to187    default to values from a parameter that came before.188189Most of the time you do not need to be concerned about any of this,190but it is important to know how it works for some advanced cases.