Skip to content
Myr

advanced.rst

This file

Path

docs/advanced.rst

488 lines · 17.1 KiB

Last changed by

Merge branch '8.0.x'David Lordbefore adoption29df879

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 (see `Command alias example16<https://github.com/pallets/click/tree/main/examples/aliases>`_).17For instance, you can configure ``git`` to accept ``git ci`` as alias for18``git commit``.  Other tools also support auto-discovery for aliases by19automatically shortening them.2021Click does not support this out of the box, but it's very easy to customize22the :class:`Group` or any other :class:`MultiCommand` to provide this23functionality.2425As explained in :ref:`custom-multi-commands`, a multi command can provide26two methods: :meth:`~MultiCommand.list_commands` and27:meth:`~MultiCommand.get_command`.  In this particular case, you only need28to override the latter as you generally don't want to enumerate the29aliases on the help page in order to avoid confusion.3031This following example implements a subclass of :class:`Group` that32accepts a prefix for a command.  If there were a command called ``push``,33it would accept ``pus`` as an alias (so long as it was unique):3435.. click:example::3637    class AliasedGroup(click.Group):38        def get_command(self, ctx, cmd_name):39            rv = click.Group.get_command(self, ctx, cmd_name)40            if rv is not None:41                return rv42            matches = [x for x in self.list_commands(ctx)43                       if x.startswith(cmd_name)]44            if not matches:45                return None46            elif len(matches) == 1:47                return click.Group.get_command(self, ctx, matches[0])48            ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")4950        def resolve_command(self, ctx, args):51            # always return the full command name52            _, cmd, args = super().resolve_command(ctx, args)53            return cmd.name, cmd, args5455And it can then be used like this:5657.. click:example::5859    @click.command(cls=AliasedGroup)60    def cli():61        pass6263    @cli.command()64    def push():65        pass6667    @cli.command()68    def pop():69        pass7071Parameter Modifications72-----------------------7374Parameters (options and arguments) are forwarded to the command callbacks75as you have seen.  One common way to prevent a parameter from being passed76to the callback is the `expose_value` argument to a parameter which hides77the parameter entirely.  The way this works is that the :class:`Context`78object has a :attr:`~Context.params` attribute which is a dictionary of79all parameters.  Whatever is in that dictionary is being passed to the80callbacks.8182This can be used to make up addition parameters.  Generally this pattern83is not recommended but in some cases it can be useful.  At the very least84it's good to know that the system works this way.8586.. click:example::8788    import urllib8990    def open_url(ctx, param, value):91        if value is not None:92            ctx.params['fp'] = urllib.urlopen(value)93            return value9495    @click.command()96    @click.option('--url', callback=open_url)97    def cli(url, fp=None):98        if fp is not None:99            click.echo(f"{url}: {fp.code}")100101In this case the callback returns the URL unchanged but also passes a102second ``fp`` value to the callback.  What's more recommended is to pass103the information in a wrapper however:104105.. click:example::106107    import urllib108109    class URL(object):110111        def __init__(self, url, fp):112            self.url = url113            self.fp = fp114115    def open_url(ctx, param, value):116        if value is not None:117            return URL(value, urllib.urlopen(value))118119    @click.command()120    @click.option('--url', callback=open_url)121    def cli(url):122        if url is not None:123            click.echo(f"{url.url}: {url.fp.code}")124125126Token Normalization127-------------------128129.. versionadded:: 2.0130131Starting with Click 2.0, it's possible to provide a function that is used132for normalizing tokens.  Tokens are option names, choice values, or command133values.  This can be used to implement case insensitive options, for134instance.135136In order to use this feature, the context needs to be passed a function that137performs the normalization of the token.  For instance, you could have a138function that converts the token to lowercase:139140.. click:example::141142    CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower())143144    @click.command(context_settings=CONTEXT_SETTINGS)145    @click.option('--name', default='Pete')146    def cli(name):147        click.echo(f"Name: {name}")148149And how it works on the command line:150151.. click:run::152153    invoke(cli, prog_name='cli', args=['--NAME=Pete'])154155Invoking Other Commands156-----------------------157158Sometimes, it might be interesting to invoke one command from another159command.  This is a pattern that is generally discouraged with Click, but160possible nonetheless.  For this, you can use the :func:`Context.invoke`161or :func:`Context.forward` methods.162163They work similarly, but the difference is that :func:`Context.invoke` merely164invokes another command with the arguments you provide as a caller,165whereas :func:`Context.forward` fills in the arguments from the current166command.  Both accept the command as the first argument and everything else167is passed onwards as you would expect.168169Example:170171.. click:example::172173    cli = click.Group()174175    @cli.command()176    @click.option('--count', default=1)177    def test(count):178        click.echo(f'Count: {count}')179180    @cli.command()181    @click.option('--count', default=1)182    @click.pass_context183    def dist(ctx, count):184        ctx.forward(test)185        ctx.invoke(test, count=42)186187And what it looks like:188189.. click:run::190191    invoke(cli, prog_name='cli', args=['dist'])192193194.. _callback-evaluation-order:195196Callback Evaluation Order197-------------------------198199Click works a bit differently than some other command line parsers in that200it attempts to reconcile the order of arguments as defined by the201programmer with the order of arguments as defined by the user before202invoking any callbacks.203204This is an important concept to understand when porting complex205patterns to Click from optparse or other systems.  A parameter206callback invocation in optparse happens as part of the parsing step,207whereas a callback invocation in Click happens after the parsing.208209The main difference is that in optparse, callbacks are invoked with the raw210value as it happens, whereas a callback in Click is invoked after the211value has been fully converted.212213Generally, the order of invocation is driven by the order in which the user214provides the arguments to the script; if there is an option called ``--foo``215and an option called ``--bar`` and the user calls it as ``--bar216--foo``, then the callback for ``bar`` will fire before the one for ``foo``.217218There are three exceptions to this rule which are important to know:219220Eagerness:221    An option can be set to be "eager".  All eager parameters are222    evaluated before all non-eager parameters, but again in the order as223    they were provided on the command line by the user.224225    This is important for parameters that execute and exit like ``--help``226    and ``--version``.  Both are eager parameters, but whatever parameter227    comes first on the command line will win and exit the program.228229Repeated parameters:230    If an option or argument is split up on the command line into multiple231    places because it is repeated -- for instance, ``--exclude foo --include232    baz --exclude bar`` -- the callback will fire based on the position of233    the first option.  In this case, the callback will fire for234    ``exclude`` and it will be passed both options (``foo`` and235    ``bar``), then the callback for ``include`` will fire with ``baz``236    only.237238    Note that even if a parameter does not allow multiple versions, Click239    will still accept the position of the first, but it will ignore every240    value except the last.  The reason for this is to allow composability241    through shell aliases that set defaults.242243Missing parameters:244    If a parameter is not defined on the command line, the callback will245    still fire.  This is different from how it works in optparse where246    undefined values do not fire the callback.  Missing parameters fire247    their callbacks at the very end which makes it possible for them to248    default to values from a parameter that came before.249250Most of the time you do not need to be concerned about any of this,251but it is important to know how it works for some advanced cases.252253.. _forwarding-unknown-options:254255Forwarding Unknown Options256--------------------------257258In some situations it is interesting to be able to accept all unknown259options for further manual processing.  Click can generally do that as of260Click 4.0, but it has some limitations that lie in the nature of the261problem.  The support for this is provided through a parser flag called262``ignore_unknown_options`` which will instruct the parser to collect all263unknown options and to put them to the leftover argument instead of264triggering a parsing error.265266This can generally be activated in two different ways:2672681.  It can be enabled on custom :class:`Command` subclasses by changing269    the :attr:`~BaseCommand.ignore_unknown_options` attribute.2702.  It can be enabled by changing the attribute of the same name on the271    context class (:attr:`Context.ignore_unknown_options`).  This is best272    changed through the ``context_settings`` dictionary on the command.273274For most situations the easiest solution is the second.  Once the behavior275is changed something needs to pick up those leftover options (which at276this point are considered arguments).  For this again you have two277options:2782791.  You can use :func:`pass_context` to get the context passed.  This will280    only work if in addition to :attr:`~Context.ignore_unknown_options`281    you also set :attr:`~Context.allow_extra_args` as otherwise the282    command will abort with an error that there are leftover arguments.283    If you go with this solution, the extra arguments will be collected in284    :attr:`Context.args`.2852.  You can attach a :func:`argument` with ``nargs`` set to `-1` which286    will eat up all leftover arguments.  In this case it's recommended to287    set the `type` to :data:`UNPROCESSED` to avoid any string processing288    on those arguments as otherwise they are forced into unicode strings289    automatically which is often not what you want.290291In the end you end up with something like this:292293.. click:example::294295    import sys296    from subprocess import call297298    @click.command(context_settings=dict(299        ignore_unknown_options=True,300    ))301    @click.option('-v', '--verbose', is_flag=True, help='Enables verbose mode')302    @click.argument('timeit_args', nargs=-1, type=click.UNPROCESSED)303    def cli(verbose, timeit_args):304        """A fake wrapper around Python's timeit."""305        cmdline = ['echo', 'python', '-mtimeit'] + list(timeit_args)306        if verbose:307            click.echo(f"Invoking: {' '.join(cmdline)}")308        call(cmdline)309310And what it looks like:311312.. click:run::313314    invoke(cli, prog_name='cli', args=['--help'])315    println()316    invoke(cli, prog_name='cli', args=['-n', '100', 'a = 1; b = 2; a * b'])317    println()318    invoke(cli, prog_name='cli', args=['-v', 'a = 1; b = 2; a * b'])319320As you can see the verbosity flag is handled by Click, everything else321ends up in the `timeit_args` variable for further processing which then322for instance, allows invoking a subprocess.  There are a few things that323are important to know about how this ignoring of unhandled flag happens:324325*   Unknown long options are generally ignored and not processed at all.326    So for instance if ``--foo=bar`` or ``--foo bar`` are passed they327    generally end up like that.  Note that because the parser cannot know328    if an option will accept an argument or not, the ``bar`` part might be329    handled as an argument.330*   Unknown short options might be partially handled and reassembled if331    necessary.  For instance in the above example there is an option332    called ``-v`` which enables verbose mode.  If the command would be333    ignored with ``-va`` then the ``-v`` part would be handled by Click334    (as it is known) and ``-a`` would end up in the leftover parameters335    for further processing.336*   Depending on what you plan on doing you might have some success by337    disabling interspersed arguments338    (:attr:`~Context.allow_interspersed_args`) which instructs the parser339    to not allow arguments and options to be mixed.  Depending on your340    situation this might improve your results.341342Generally though the combinated handling of options and arguments from343your own commands and commands from another application are discouraged344and if you can avoid it, you should.  It's a much better idea to have345everything below a subcommand be forwarded to another application than to346handle some arguments yourself.347348349Global Context Access350---------------------351352.. versionadded:: 5.0353354Starting with Click 5.0 it is possible to access the current context from355anywhere within the same thread through the use of the356:func:`get_current_context` function which returns it.  This is primarily357useful for accessing the context bound object as well as some flags that358are stored on it to customize the runtime behavior.  For instance the359:func:`echo` function does this to infer the default value of the `color`360flag.361362Example usage::363364    def get_current_command_name():365        return click.get_current_context().info_name366367It should be noted that this only works within the current thread.  If you368spawn additional threads then those threads will not have the ability to369refer to the current context.  If you want to give another thread the370ability to refer to this context you need to use the context within the371thread as a context manager::372373    def spawn_thread(ctx, func):374        def wrapper():375            with ctx:376                func()377        t = threading.Thread(target=wrapper)378        t.start()379        return t380381Now the thread function can access the context like the main thread would382do.  However if you do use this for threading you need to be very careful383as the vast majority of the context is not thread safe!  You are only384allowed to read from the context, but not to perform any modifications on385it.386387388Detecting the Source of a Parameter389-----------------------------------390391In some situations it's helpful to understand whether or not an option392or parameter came from the command line, the environment, the default393value, or :attr:`Context.default_map`. The394:meth:`Context.get_parameter_source` method can be used to find this395out. It will return a member of the :class:`~click.core.ParameterSource`396enum.397398.. click:example::399400    @click.command()401    @click.argument('port', nargs=1, default=8080, envvar="PORT")402    @click.pass_context403    def cli(ctx, port):404        source = ctx.get_parameter_source("port")405        click.echo(f"Port came from {source.name}")406407.. click:run::408409    invoke(cli, prog_name='cli', args=['8080'])410    println()411    invoke(cli, prog_name='cli', args=[], env={"PORT": "8080"})412    println()413    invoke(cli, prog_name='cli', args=[])414    println()415416417Managing Resources418------------------419420It can be useful to open a resource in a group, to be made available to421subcommands. Many types of resources need to be closed or otherwise422cleaned up after use. The standard way to do this in Python is by using423a context manager with the ``with`` statement.424425For example, the ``Repo`` class from :doc:`complex` might actually be426defined as a context manager:427428.. code-block:: python429430    class Repo:431        def __init__(self, home=None):432            self.home = os.path.abspath(home or ".")433            self.db = None434435        def __enter__(self):436            path = os.path.join(self.home, "repo.db")437            self.db = open_database(path)438439        def __exit__(self, exc_type, exc_value, tb):440            self.db.close()441442Ordinarily, it would be used with the ``with`` statement:443444.. code-block:: python445446    with Repo() as repo:447        repo.db.query(...)448449However, a ``with`` block in a group would exit and close the database450before it could be used by a subcommand.451452Instead, use the context's :meth:`~click.Context.with_resource` method453to enter the context manager and return the resource. When the group and454any subcommands finish, the context's resources are cleaned up.455456.. code-block:: python457458    @click.group()459    @click.option("--repo-home", default=".repo")460    @click.pass_context461    def cli(ctx, repo_home):462        ctx.obj = ctx.with_resource(Repo(repo_home))463464    @cli.command()465    @click.pass_obj466    def log(obj):467        # obj is the repo opened in the cli group468        for entry in obj.db.query(...):469            click.echo(entry)470471If the resource isn't a context manager, usually it can be wrapped in472one using something from :mod:`contextlib`. If that's not possible, use473the context's :meth:`~click.Context.call_on_close` method to register a474cleanup function.475476.. code-block:: python477478    @click.group()479    @click.option("--name", default="repo.db")480    @click.pass_context481    def cli(ctx, repo_home):482        ctx.obj = db = open_db(repo_home)483484        @ctx.call_on_close485        def close_db():486            db.record_use()487            db.save()488            db.close()