Skip to content
Myr

advanced.rst

This file

Path

docs/advanced.rst

495 lines · 17.0 KiB

Last changed by

deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc

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.91011.. _aliases:1213Command Aliases14---------------1516Many tools support aliases for commands. For example, you can configure17``git`` to accept ``git ci`` as alias for ``git commit``. Other tools also18support auto-discovery for aliases by automatically shortening them.1920It's possible to customize :class:`Group` to provide this functionality. As21explained in :ref:`custom-groups`, a group provides two methods:22:meth:`~Group.list_commands` and :meth:`~Group.get_command`. In this particular23case, you only need to override the latter as you generally don't want to24enumerate the aliases on the help page in order to avoid confusion.2526The following example implements a subclass of :class:`Group` that accepts a27prefix for a command. If there was a command called ``push``, it would accept28``pus`` as an alias (so long as it was unique):2930.. click:example::3132    class AliasedGroup(click.Group):33        def get_command(self, ctx, cmd_name):34            rv = super().get_command(ctx, cmd_name)3536            if rv is not None:37                return rv3839            matches = [40                x for x in self.list_commands(ctx)41                if x.startswith(cmd_name)42            ]4344            if not matches:45                return None4647            if len(matches) == 1:48                return click.Group.get_command(self, ctx, matches[0])4950            ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")5152        def resolve_command(self, ctx, args):53            # always return the full command name54            _, cmd, args = super().resolve_command(ctx, args)55            return cmd.name, cmd, args5657It can be used like this:5859.. click:example::6061    @click.group(cls=AliasedGroup)62    def cli():63        pass6465    @cli.command66    def push():67        pass6869    @cli.command70    def pop():71        pass7273See the `alias example`_ in Click's repository for another example.7475.. _alias example: https://github.com/pallets/click/tree/main/examples/aliases767778Parameter Modifications79-----------------------8081Parameters (options and arguments) are forwarded to the command callbacks82as you have seen.  One common way to prevent a parameter from being passed83to the callback is the `expose_value` argument to a parameter which hides84the parameter entirely.  The way this works is that the :class:`Context`85object has a :attr:`~Context.params` attribute which is a dictionary of86all parameters.  Whatever is in that dictionary is being passed to the87callbacks.8889This can be used to make up additional parameters.  Generally this pattern90is not recommended but in some cases it can be useful.  At the very least91it's good to know that the system works this way.9293.. click:example::9495    import urllib9697    def open_url(ctx, param, value):98        if value is not None:99            ctx.params['fp'] = urllib.urlopen(value)100            return value101102    @click.command()103    @click.option('--url', callback=open_url)104    def cli(url, fp=None):105        if fp is not None:106            click.echo(f"{url}: {fp.code}")107108In this case the callback returns the URL unchanged but also passes a109second ``fp`` value to the callback.  What's more recommended is to pass110the information in a wrapper however:111112.. click:example::113114    import urllib115116    class URL(object):117118        def __init__(self, url, fp):119            self.url = url120            self.fp = fp121122    def open_url(ctx, param, value):123        if value is not None:124            return URL(value, urllib.urlopen(value))125126    @click.command()127    @click.option('--url', callback=open_url)128    def cli(url):129        if url is not None:130            click.echo(f"{url.url}: {url.fp.code}")131132133Token Normalization134-------------------135136.. versionadded:: 2.0137138Starting with Click 2.0, it's possible to provide a function that is used139for normalizing tokens.  Tokens are option names, choice values, or command140values.  This can be used to implement case insensitive options, for141instance.142143In order to use this feature, the context needs to be passed a function that144performs the normalization of the token.  For instance, you could have a145function that converts the token to lowercase:146147.. click:example::148149    CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower())150151    @click.command(context_settings=CONTEXT_SETTINGS)152    @click.option('--name', default='Pete')153    def cli(name):154        click.echo(f"Name: {name}")155156And how it works on the command line:157158.. click:run::159160    invoke(cli, prog_name='cli', args=['--NAME=Pete'])161162Invoking Other Commands163-----------------------164165Sometimes, it might be interesting to invoke one command from another166command.  This is a pattern that is generally discouraged with Click, but167possible nonetheless.  For this, you can use the :func:`Context.invoke`168or :func:`Context.forward` methods.169170They work similarly, but the difference is that :func:`Context.invoke` merely171invokes another command with the arguments you provide as a caller,172whereas :func:`Context.forward` fills in the arguments from the current173command.  Both accept the command as the first argument and everything else174is passed onwards as you would expect.175176Example:177178.. click:example::179180    cli = click.Group()181182    @cli.command()183    @click.option('--count', default=1)184    def test(count):185        click.echo(f'Count: {count}')186187    @cli.command()188    @click.option('--count', default=1)189    @click.pass_context190    def dist(ctx, count):191        ctx.forward(test)192        ctx.invoke(test, count=42)193194And what it looks like:195196.. click:run::197198    invoke(cli, prog_name='cli', args=['dist'])199200201.. _callback-evaluation-order:202203Callback Evaluation Order204-------------------------205206Click works a bit differently than some other command line parsers in that207it attempts to reconcile the order of arguments as defined by the208programmer with the order of arguments as defined by the user before209invoking any callbacks.210211This is an important concept to understand when porting complex212patterns to Click from optparse or other systems.  A parameter213callback invocation in optparse happens as part of the parsing step,214whereas a callback invocation in Click happens after the parsing.215216The main difference is that in optparse, callbacks are invoked with the raw217value as it happens, whereas a callback in Click is invoked after the218value has been fully converted.219220Generally, the order of invocation is driven by the order in which the user221provides the arguments to the script; if there is an option called ``--foo``222and an option called ``--bar`` and the user calls it as ``--bar223--foo``, then the callback for ``bar`` will fire before the one for ``foo``.224225There are three exceptions to this rule which are important to know:226227Eagerness:228    An option can be set to be "eager".  All eager parameters are229    evaluated before all non-eager parameters, but again in the order as230    they were provided on the command line by the user.231232    This is important for parameters that execute and exit like ``--help``233    and ``--version``.  Both are eager parameters, but whatever parameter234    comes first on the command line will win and exit the program.235236Repeated parameters:237    If an option or argument is split up on the command line into multiple238    places because it is repeated -- for instance, ``--exclude foo --include239    baz --exclude bar`` -- the callback will fire based on the position of240    the first option.  In this case, the callback will fire for241    ``exclude`` and it will be passed both options (``foo`` and242    ``bar``), then the callback for ``include`` will fire with ``baz``243    only.244245    Note that even if a parameter does not allow multiple versions, Click246    will still accept the position of the first, but it will ignore every247    value except the last.  The reason for this is to allow composability248    through shell aliases that set defaults.249250Missing parameters:251    If a parameter is not defined on the command line, the callback will252    still fire.  This is different from how it works in optparse where253    undefined values do not fire the callback.  Missing parameters fire254    their callbacks at the very end which makes it possible for them to255    default to values from a parameter that came before.256257Most of the time you do not need to be concerned about any of this,258but it is important to know how it works for some advanced cases.259260.. _forwarding-unknown-options:261262Forwarding Unknown Options263--------------------------264265In some situations it is interesting to be able to accept all unknown266options for further manual processing.  Click can generally do that as of267Click 4.0, but it has some limitations that lie in the nature of the268problem.  The support for this is provided through a parser flag called269``ignore_unknown_options`` which will instruct the parser to collect all270unknown options and to put them to the leftover argument instead of271triggering a parsing error.272273This can generally be activated in two different ways:2742751.  It can be enabled on custom :class:`Command` subclasses by changing276    the :attr:`~Command.ignore_unknown_options` attribute.2772.  It can be enabled by changing the attribute of the same name on the278    context class (:attr:`Context.ignore_unknown_options`).  This is best279    changed through the ``context_settings`` dictionary on the command.280281For most situations the easiest solution is the second.  Once the behavior282is changed something needs to pick up those leftover options (which at283this point are considered arguments).  For this again you have two284options:2852861.  You can use :func:`pass_context` to get the context passed.  This will287    only work if in addition to :attr:`~Context.ignore_unknown_options`288    you also set :attr:`~Context.allow_extra_args` as otherwise the289    command will abort with an error that there are leftover arguments.290    If you go with this solution, the extra arguments will be collected in291    :attr:`Context.args`.2922.  You can attach an :func:`argument` with ``nargs`` set to `-1` which293    will eat up all leftover arguments.  In this case it's recommended to294    set the `type` to :data:`UNPROCESSED` to avoid any string processing295    on those arguments as otherwise they are forced into unicode strings296    automatically which is often not what you want.297298In the end you end up with something like this:299300.. click:example::301302    import sys303    from subprocess import call304305    @click.command(context_settings=dict(306        ignore_unknown_options=True,307    ))308    @click.option('-v', '--verbose', is_flag=True, help='Enables verbose mode')309    @click.argument('timeit_args', nargs=-1, type=click.UNPROCESSED)310    def cli(verbose, timeit_args):311        """A fake wrapper around Python's timeit."""312        cmdline = ['echo', 'python', '-mtimeit'] + list(timeit_args)313        if verbose:314            click.echo(f"Invoking: {' '.join(cmdline)}")315        call(cmdline)316317And what it looks like:318319.. click:run::320321    invoke(cli, prog_name='cli', args=['--help'])322    println()323    invoke(cli, prog_name='cli', args=['-n', '100', 'a = 1; b = 2; a * b'])324    println()325    invoke(cli, prog_name='cli', args=['-v', 'a = 1; b = 2; a * b'])326327As you can see the verbosity flag is handled by Click, everything else328ends up in the `timeit_args` variable for further processing which then329for instance, allows invoking a subprocess.  There are a few things that330are important to know about how this ignoring of unhandled flag happens:331332*   Unknown long options are generally ignored and not processed at all.333    So for instance if ``--foo=bar`` or ``--foo bar`` are passed they334    generally end up like that.  Note that because the parser cannot know335    if an option will accept an argument or not, the ``bar`` part might be336    handled as an argument.337*   Unknown short options might be partially handled and reassembled if338    necessary.  For instance in the above example there is an option339    called ``-v`` which enables verbose mode.  If the command would be340    ignored with ``-va`` then the ``-v`` part would be handled by Click341    (as it is known) and ``-a`` would end up in the leftover parameters342    for further processing.343*   Depending on what you plan on doing you might have some success by344    disabling interspersed arguments345    (:attr:`~Context.allow_interspersed_args`) which instructs the parser346    to not allow arguments and options to be mixed.  Depending on your347    situation this might improve your results.348349Generally though the combined handling of options and arguments from350your own commands and commands from another application are discouraged351and if you can avoid it, you should.  It's a much better idea to have352everything below a subcommand be forwarded to another application than to353handle some arguments yourself.354355356Global Context Access357---------------------358359.. versionadded:: 5.0360361Starting with Click 5.0 it is possible to access the current context from362anywhere within the same thread through the use of the363:func:`get_current_context` function which returns it.  This is primarily364useful for accessing the context bound object as well as some flags that365are stored on it to customize the runtime behavior.  For instance the366:func:`echo` function does this to infer the default value of the `color`367flag.368369Example usage::370371    def get_current_command_name():372        return click.get_current_context().info_name373374It should be noted that this only works within the current thread.  If you375spawn additional threads then those threads will not have the ability to376refer to the current context.  If you want to give another thread the377ability to refer to this context you need to use the context within the378thread as a context manager::379380    def spawn_thread(ctx, func):381        def wrapper():382            with ctx:383                func()384        t = threading.Thread(target=wrapper)385        t.start()386        return t387388Now the thread function can access the context like the main thread would389do.  However if you do use this for threading you need to be very careful390as the vast majority of the context is not thread safe!  You are only391allowed to read from the context, but not to perform any modifications on392it.393394395Detecting the Source of a Parameter396-----------------------------------397398In some situations it's helpful to understand whether or not an option399or parameter came from the command line, the environment, the default400value, or :attr:`Context.default_map`. The401:meth:`Context.get_parameter_source` method can be used to find this402out. It will return a member of the :class:`~click.core.ParameterSource`403enum.404405.. click:example::406407    @click.command()408    @click.argument('port', nargs=1, default=8080, envvar="PORT")409    @click.pass_context410    def cli(ctx, port):411        source = ctx.get_parameter_source("port")412        click.echo(f"Port came from {source.name}")413414.. click:run::415416    invoke(cli, prog_name='cli', args=['8080'])417    println()418    invoke(cli, prog_name='cli', args=[], env={"PORT": "8080"})419    println()420    invoke(cli, prog_name='cli', args=[])421    println()422423424Managing Resources425------------------426427It can be useful to open a resource in a group, to be made available to428subcommands. Many types of resources need to be closed or otherwise429cleaned up after use. The standard way to do this in Python is by using430a context manager with the ``with`` statement.431432For example, the ``Repo`` class from :doc:`complex` might actually be433defined as a context manager:434435.. code-block:: python436437    class Repo:438        def __init__(self, home=None):439            self.home = os.path.abspath(home or ".")440            self.db = None441442        def __enter__(self):443            path = os.path.join(self.home, "repo.db")444            self.db = open_database(path)445446        def __exit__(self, exc_type, exc_value, tb):447            self.db.close()448449Ordinarily, it would be used with the ``with`` statement:450451.. code-block:: python452453    with Repo() as repo:454        repo.db.query(...)455456However, a ``with`` block in a group would exit and close the database457before it could be used by a subcommand.458459Instead, use the context's :meth:`~click.Context.with_resource` method460to enter the context manager and return the resource. When the group and461any subcommands finish, the context's resources are cleaned up.462463.. code-block:: python464465    @click.group()466    @click.option("--repo-home", default=".repo")467    @click.pass_context468    def cli(ctx, repo_home):469        ctx.obj = ctx.with_resource(Repo(repo_home))470471    @cli.command()472    @click.pass_obj473    def log(obj):474        # obj is the repo opened in the cli group475        for entry in obj.db.query(...):476            click.echo(entry)477478If the resource isn't a context manager, usually it can be wrapped in479one using something from :mod:`contextlib`. If that's not possible, use480the context's :meth:`~click.Context.call_on_close` method to register a481cleanup function.482483.. code-block:: python484485    @click.group()486    @click.option("--name", default="repo.db")487    @click.pass_context488    def cli(ctx, repo_home):489        ctx.obj = db = open_db(repo_home)490491        @ctx.call_on_close492        def close_db():493            db.record_use()494            db.save()495            db.close()