advanced.rst
This file
Path
docs/advanced.rst
564 lines · 18.9 KiB
Last changed by
Fill in a lot of missing command and group docs.Edward Gbefore adoptione2f2d84
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.. contents::11 :depth: 112 :local:1314.. _custom-groups:1516Custom Groups17-------------1819You can customize the behavior of a group beyond the arguments it accepts by20subclassing :class:`click.Group`.2122The most common methods to override are :meth:`~click.Group.get_command` and23:meth:`~click.Group.list_commands`.2425The following example implements a basic plugin system that loads commands from26Python files in a folder. The command is lazily loaded to avoid slow startup.2728.. code-block:: python2930 import importlib.util31 import os32 import click3334 class PluginGroup(click.Group):35 def __init__(self, name=None, plugin_folder="commands", **kwargs):36 super().__init__(name=name, **kwargs)37 self.plugin_folder = plugin_folder3839 def list_commands(self, ctx):40 rv = []4142 for filename in os.listdir(self.plugin_folder):43 if filename.endswith(".py"):44 rv.append(filename[:-3])4546 rv.sort()47 return rv4849 def get_command(self, ctx, name):50 path = os.path.join(self.plugin_folder, f"{name}.py")51 spec = importlib.util.spec_from_file_location(name, path)52 module = importlib.util.module_from_spec(spec)53 spec.loader.exec_module(module)54 return module.cli5556 cli = PluginGroup(57 plugin_folder=os.path.join(os.path.dirname(__file__), "commands")58 )5960 if __name__ == "__main__":61 cli()6263Custom classes can also be used with decorators:6465.. code-block:: python6667 @click.group(68 cls=PluginGroup,69 plugin_folder=os.path.join(os.path.dirname(__file__), "commands")70 )71 def cli():72 pass7374.. _aliases:7576Command Aliases77---------------7879Many tools support aliases for commands. For example, you can configure80``git`` to accept ``git ci`` as alias for ``git commit``. Other tools also81support auto-discovery for aliases by automatically shortening them.8283It's possible to customize :class:`Group` to provide this functionality. As84explained in :ref:`custom-groups`, a group provides two methods:85:meth:`~Group.list_commands` and :meth:`~Group.get_command`. In this particular86case, you only need to override the latter as you generally don't want to87enumerate the aliases on the help page in order to avoid confusion.8889The following example implements a subclass of :class:`Group` that accepts a90prefix for a command. If there was a command called ``push``, it would accept91``pus`` as an alias (so long as it was unique):9293.. click:example::9495 class AliasedGroup(click.Group):96 def get_command(self, ctx, cmd_name):97 rv = super().get_command(ctx, cmd_name)9899 if rv is not None:100 return rv101102 matches = [103 x for x in self.list_commands(ctx)104 if x.startswith(cmd_name)105 ]106107 if not matches:108 return None109110 if len(matches) == 1:111 return click.Group.get_command(self, ctx, matches[0])112113 ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")114115 def resolve_command(self, ctx, args):116 # always return the full command name117 _, cmd, args = super().resolve_command(ctx, args)118 return cmd.name, cmd, args119120It can be used like this:121122.. click:example::123124 @click.group(cls=AliasedGroup)125 def cli():126 pass127128 @cli.command129 def push():130 pass131132 @cli.command133 def pop():134 pass135136See the `alias example`_ in Click's repository for another example.137138.. _alias example: https://github.com/pallets/click/tree/main/examples/aliases139140141Parameter Modifications142-----------------------143144Parameters (options and arguments) are forwarded to the command callbacks145as you have seen. One common way to prevent a parameter from being passed146to the callback is the `expose_value` argument to a parameter which hides147the parameter entirely. The way this works is that the :class:`Context`148object has a :attr:`~Context.params` attribute which is a dictionary of149all parameters. Whatever is in that dictionary is being passed to the150callbacks.151152This can be used to make up additional parameters. Generally this pattern153is not recommended but in some cases it can be useful. At the very least154it's good to know that the system works this way.155156.. click:example::157158 import urllib159160 def open_url(ctx, param, value):161 if value is not None:162 ctx.params['fp'] = urllib.urlopen(value)163 return value164165 @click.command()166 @click.option('--url', callback=open_url)167 def cli(url, fp=None):168 if fp is not None:169 click.echo(f"{url}: {fp.code}")170171In this case the callback returns the URL unchanged but also passes a172second ``fp`` value to the callback. What's more recommended is to pass173the information in a wrapper however:174175.. click:example::176177 import urllib178179 class URL(object):180181 def __init__(self, url, fp):182 self.url = url183 self.fp = fp184185 def open_url(ctx, param, value):186 if value is not None:187 return URL(value, urllib.urlopen(value))188189 @click.command()190 @click.option('--url', callback=open_url)191 def cli(url):192 if url is not None:193 click.echo(f"{url.url}: {url.fp.code}")194195196Token Normalization197-------------------198199.. versionadded:: 2.0200201Starting with Click 2.0, it's possible to provide a function that is used202for normalizing tokens. Tokens are option names, choice values, or command203values. This can be used to implement case insensitive options, for204instance.205206In order to use this feature, the context needs to be passed a function that207performs the normalization of the token. For instance, you could have a208function that converts the token to lowercase:209210.. click:example::211212 CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower())213214 @click.command(context_settings=CONTEXT_SETTINGS)215 @click.option('--name', default='Pete')216 def cli(name):217 click.echo(f"Name: {name}")218219And how it works on the command line:220221.. click:run::222223 invoke(cli, prog_name='cli', args=['--NAME=Pete'])224225Invoking Other Commands226-----------------------227228Sometimes, it might be interesting to invoke one command from another229command. This is a pattern that is generally discouraged with Click, but230possible nonetheless. For this, you can use the :func:`Context.invoke`231or :func:`Context.forward` methods.232233They work similarly, but the difference is that :func:`Context.invoke` merely234invokes another command with the arguments you provide as a caller,235whereas :func:`Context.forward` fills in the arguments from the current236command. Both accept the command as the first argument and everything else237is passed onwards as you would expect.238239Example:240241.. click:example::242243 cli = click.Group()244245 @cli.command()246 @click.option('--count', default=1)247 def test(count):248 click.echo(f'Count: {count}')249250 @cli.command()251 @click.option('--count', default=1)252 @click.pass_context253 def dist(ctx, count):254 ctx.forward(test)255 ctx.invoke(test, count=42)256257And what it looks like:258259.. click:run::260261 invoke(cli, prog_name='cli', args=['dist'])262263264.. _callback-evaluation-order:265266Callback Evaluation Order267-------------------------268269Click works a bit differently than some other command line parsers in that270it attempts to reconcile the order of arguments as defined by the271programmer with the order of arguments as defined by the user before272invoking any callbacks.273274This is an important concept to understand when porting complex275patterns to Click from optparse or other systems. A parameter276callback invocation in optparse happens as part of the parsing step,277whereas a callback invocation in Click happens after the parsing.278279The main difference is that in optparse, callbacks are invoked with the raw280value as it happens, whereas a callback in Click is invoked after the281value has been fully converted.282283Generally, the order of invocation is driven by the order in which the user284provides the arguments to the script; if there is an option called ``--foo``285and an option called ``--bar`` and the user calls it as ``--bar286--foo``, then the callback for ``bar`` will fire before the one for ``foo``.287288There are three exceptions to this rule which are important to know:289290Eagerness:291 An option can be set to be "eager". All eager parameters are292 evaluated before all non-eager parameters, but again in the order as293 they were provided on the command line by the user.294295 This is important for parameters that execute and exit like ``--help``296 and ``--version``. Both are eager parameters, but whatever parameter297 comes first on the command line will win and exit the program.298299Repeated parameters:300 If an option or argument is split up on the command line into multiple301 places because it is repeated -- for instance, ``--exclude foo --include302 baz --exclude bar`` -- the callback will fire based on the position of303 the first option. In this case, the callback will fire for304 ``exclude`` and it will be passed both options (``foo`` and305 ``bar``), then the callback for ``include`` will fire with ``baz``306 only.307308 Note that even if a parameter does not allow multiple versions, Click309 will still accept the position of the first, but it will ignore every310 value except the last. The reason for this is to allow composability311 through shell aliases that set defaults.312313Missing parameters:314 If a parameter is not defined on the command line, the callback will315 still fire. This is different from how it works in optparse where316 undefined values do not fire the callback. Missing parameters fire317 their callbacks at the very end which makes it possible for them to318 default to values from a parameter that came before.319320Most of the time you do not need to be concerned about any of this,321but it is important to know how it works for some advanced cases.322323.. _forwarding-unknown-options:324325Forwarding Unknown Options326--------------------------327328In some situations it is interesting to be able to accept all unknown329options for further manual processing. Click can generally do that as of330Click 4.0, but it has some limitations that lie in the nature of the331problem. The support for this is provided through a parser flag called332``ignore_unknown_options`` which will instruct the parser to collect all333unknown options and to put them to the leftover argument instead of334triggering a parsing error.335336This can generally be activated in two different ways:3373381. It can be enabled on custom :class:`Command` subclasses by changing339 the :attr:`~Command.ignore_unknown_options` attribute.3402. It can be enabled by changing the attribute of the same name on the341 context class (:attr:`Context.ignore_unknown_options`). This is best342 changed through the ``context_settings`` dictionary on the command.343344For most situations the easiest solution is the second. Once the behavior345is changed something needs to pick up those leftover options (which at346this point are considered arguments). For this again you have two347options:3483491. You can use :func:`pass_context` to get the context passed. This will350 only work if in addition to :attr:`~Context.ignore_unknown_options`351 you also set :attr:`~Context.allow_extra_args` as otherwise the352 command will abort with an error that there are leftover arguments.353 If you go with this solution, the extra arguments will be collected in354 :attr:`Context.args`.3552. You can attach an :func:`argument` with ``nargs`` set to `-1` which356 will eat up all leftover arguments. In this case it's recommended to357 set the `type` to :data:`UNPROCESSED` to avoid any string processing358 on those arguments as otherwise they are forced into unicode strings359 automatically which is often not what you want.360361In the end you end up with something like this:362363.. click:example::364365 import sys366 from subprocess import call367368 @click.command(context_settings=dict(369 ignore_unknown_options=True,370 ))371 @click.option('-v', '--verbose', is_flag=True, help='Enables verbose mode')372 @click.argument('timeit_args', nargs=-1, type=click.UNPROCESSED)373 def cli(verbose, timeit_args):374 """A fake wrapper around Python's timeit."""375 cmdline = ['echo', 'python', '-mtimeit'] + list(timeit_args)376 if verbose:377 click.echo(f"Invoking: {' '.join(cmdline)}")378 call(cmdline)379380And what it looks like:381382.. click:run::383384 invoke(cli, prog_name='cli', args=['--help'])385 println()386 invoke(cli, prog_name='cli', args=['-n', '100', 'a = 1; b = 2; a * b'])387 println()388 invoke(cli, prog_name='cli', args=['-v', 'a = 1; b = 2; a * b'])389390As you can see the verbosity flag is handled by Click, everything else391ends up in the `timeit_args` variable for further processing which then392for instance, allows invoking a subprocess. There are a few things that393are important to know about how this ignoring of unhandled flag happens:394395* Unknown long options are generally ignored and not processed at all.396 So for instance if ``--foo=bar`` or ``--foo bar`` are passed they397 generally end up like that. Note that because the parser cannot know398 if an option will accept an argument or not, the ``bar`` part might be399 handled as an argument.400* Unknown short options might be partially handled and reassembled if401 necessary. For instance in the above example there is an option402 called ``-v`` which enables verbose mode. If the command would be403 ignored with ``-va`` then the ``-v`` part would be handled by Click404 (as it is known) and ``-a`` would end up in the leftover parameters405 for further processing.406* Depending on what you plan on doing you might have some success by407 disabling interspersed arguments408 (:attr:`~Context.allow_interspersed_args`) which instructs the parser409 to not allow arguments and options to be mixed. Depending on your410 situation this might improve your results.411412Generally though the combined handling of options and arguments from413your own commands and commands from another application are discouraged414and if you can avoid it, you should. It's a much better idea to have415everything below a subcommand be forwarded to another application than to416handle some arguments yourself.417418419Global Context Access420---------------------421422.. versionadded:: 5.0423424Starting with Click 5.0 it is possible to access the current context from425anywhere within the same thread through the use of the426:func:`get_current_context` function which returns it. This is primarily427useful for accessing the context bound object as well as some flags that428are stored on it to customize the runtime behavior. For instance the429:func:`echo` function does this to infer the default value of the `color`430flag.431432Example usage::433434 def get_current_command_name():435 return click.get_current_context().info_name436437It should be noted that this only works within the current thread. If you438spawn additional threads then those threads will not have the ability to439refer to the current context. If you want to give another thread the440ability to refer to this context you need to use the context within the441thread as a context manager::442443 def spawn_thread(ctx, func):444 def wrapper():445 with ctx:446 func()447 t = threading.Thread(target=wrapper)448 t.start()449 return t450451Now the thread function can access the context like the main thread would452do. However if you do use this for threading you need to be very careful453as the vast majority of the context is not thread safe! You are only454allowed to read from the context, but not to perform any modifications on455it.456457458Detecting the Source of a Parameter459-----------------------------------460461In some situations it's helpful to understand whether or not an option462or parameter came from the command line, the environment, the default463value, or :attr:`Context.default_map`. The464:meth:`Context.get_parameter_source` method can be used to find this465out. It will return a member of the :class:`~click.core.ParameterSource`466enum.467468.. click:example::469470 @click.command()471 @click.argument('port', nargs=1, default=8080, envvar="PORT")472 @click.pass_context473 def cli(ctx, port):474 source = ctx.get_parameter_source("port")475 click.echo(f"Port came from {source.name}")476477.. click:run::478479 invoke(cli, prog_name='cli', args=['8080'])480 println()481 invoke(cli, prog_name='cli', args=[], env={"PORT": "8080"})482 println()483 invoke(cli, prog_name='cli', args=[])484 println()485486487Managing Resources488------------------489490It can be useful to open a resource in a group, to be made available to491subcommands. Many types of resources need to be closed or otherwise492cleaned up after use. The standard way to do this in Python is by using493a context manager with the ``with`` statement.494495For example, the ``Repo`` class from :doc:`complex` might actually be496defined as a context manager:497498.. code-block:: python499500 class Repo:501 def __init__(self, home=None):502 self.home = os.path.abspath(home or ".")503 self.db = None504505 def __enter__(self):506 path = os.path.join(self.home, "repo.db")507 self.db = open_database(path)508 return self509510 def __exit__(self, exc_type, exc_value, tb):511 self.db.close()512513Ordinarily, it would be used with the ``with`` statement:514515.. code-block:: python516517 with Repo() as repo:518 repo.db.query(...)519520However, a ``with`` block in a group would exit and close the database521before it could be used by a subcommand.522523Instead, use the context's :meth:`~click.Context.with_resource` method524to enter the context manager and return the resource. When the group and525any subcommands finish, the context's resources are cleaned up.526527.. code-block:: python528529 @click.group()530 @click.option("--repo-home", default=".repo")531 @click.pass_context532 def cli(ctx, repo_home):533 ctx.obj = ctx.with_resource(Repo(repo_home))534535 @cli.command()536 @click.pass_obj537 def log(obj):538 # obj is the repo opened in the cli group539 for entry in obj.db.query(...):540 click.echo(entry)541542If the resource isn't a context manager, usually it can be wrapped in543one using something from :mod:`contextlib`. If that's not possible, use544the context's :meth:`~click.Context.call_on_close` method to register a545cleanup function.546547.. code-block:: python548549 @click.group()550 @click.option("--name", default="repo.db")551 @click.pass_context552 def cli(ctx, repo_home):553 ctx.obj = db = open_db(repo_home)554555 @ctx.call_on_close556 def close_db():557 db.record_use()558 db.save()559 db.close()560561562.. versionchanged:: 8.2 ``Context.call_on_close`` and context managers registered563 via ``Context.with_resource`` will be closed when the CLI exits. These were564 previously not called on exit.