Skip to content
Myr

advanced.rst

This file

Path

docs/advanced.rst

408 lines · 13.8 KiB

Last changed by

Make distinct sections for advanced patterns and extending click. (#2925)Rowlando13before adoption2aecb2d

History of this file

Take it

1Advanced Patterns2=================34.. currentmodule:: click56In addition to common functionality, Click offers some advanced features.78.. contents::9    :depth: 110    :local:1112Callbacks and Eager Options13---------------------------1415Sometimes, you want a parameter to completely change the execution flow.16For instance, this is the case when you want to have a ``--version``17parameter that prints out the version and then exits the application.1819Note: an actual implementation of a ``--version`` parameter that is20reusable is available in Click as :func:`click.version_option`.  The code21here is merely an example of how to implement such a flag.2223In such cases, you need two concepts: eager parameters and a callback.  An24eager parameter is a parameter that is handled before others, and a25callback is what executes after the parameter is handled.  The eagerness26is necessary so that an earlier required parameter does not produce an27error message.  For instance, if ``--version`` was not eager and a28parameter ``--foo`` was required and defined before, you would need to29specify it for ``--version`` to work.  For more information, see30:ref:`callback-evaluation-order`.3132A callback is a function that is invoked with three parameters: the33current :class:`Context`, the current :class:`Parameter`, and the value.34The context provides some useful features such as quitting the35application and gives access to other already processed parameters.3637Here's an example for a ``--version`` flag:3839.. click:example::4041    def print_version(ctx, param, value):42        if not value or ctx.resilient_parsing:43            return44        click.echo('Version 1.0')45        ctx.exit()4647    @click.command()48    @click.option('--version', is_flag=True, callback=print_version,49                  expose_value=False, is_eager=True)50    def hello():51        click.echo('Hello World!')5253The `expose_value` parameter prevents the pretty pointless ``version``54parameter from being passed to the callback.  If that was not specified, a55boolean would be passed to the `hello` script.  The `resilient_parsing`56flag is applied to the context if Click wants to parse the command line57without any destructive behavior that would change the execution flow.  In58this case, because we would exit the program, we instead do nothing.5960What it looks like:6162.. click:run::6364    invoke(hello)65    invoke(hello, args=['--version'])6667Callbacks for Validation68------------------------6970.. versionchanged:: 2.07172If you want to apply custom validation logic, you can do this in the73parameter callbacks. These callbacks can both modify values as well as74raise errors if the validation does not work. The callback runs after75type conversion. It is called for all sources, including prompts.7677In Click 1.0, you can only raise the :exc:`UsageError` but starting with78Click 2.0, you can also raise the :exc:`BadParameter` error, which has the79added advantage that it will automatically format the error message to80also contain the parameter name.8182.. click:example::8384    def validate_rolls(ctx, param, value):85        if isinstance(value, tuple):86            return value8788        try:89            rolls, _, dice = value.partition("d")90            return int(dice), int(rolls)91        except ValueError:92            raise click.BadParameter("format must be 'NdM'")9394    @click.command()95    @click.option(96        "--rolls", type=click.UNPROCESSED, callback=validate_rolls,97        default="1d6", prompt=True,98    )99    def roll(rolls):100        sides, times = rolls101        click.echo(f"Rolling a {sides}-sided dice {times} time(s)")102103.. click:run::104105    invoke(roll, args=["--rolls=42"])106    println()107    invoke(roll, args=["--rolls=2d12"])108    println()109    invoke(roll, input=["42", "2d12"])110111Parameter Modifications112-----------------------113114Parameters (options and arguments) are forwarded to the command callbacks115as you have seen.  One common way to prevent a parameter from being passed116to the callback is the `expose_value` argument to a parameter which hides117the parameter entirely.  The way this works is that the :class:`Context`118object has a :attr:`~Context.params` attribute which is a dictionary of119all parameters.  Whatever is in that dictionary is being passed to the120callbacks.121122This can be used to make up additional parameters.  Generally this pattern123is not recommended but in some cases it can be useful.  At the very least124it's good to know that the system works this way.125126.. click:example::127128    import urllib129130    def open_url(ctx, param, value):131        if value is not None:132            ctx.params['fp'] = urllib.urlopen(value)133            return value134135    @click.command()136    @click.option('--url', callback=open_url)137    def cli(url, fp=None):138        if fp is not None:139            click.echo(f"{url}: {fp.code}")140141In this case the callback returns the URL unchanged but also passes a142second ``fp`` value to the callback.  What's more recommended is to pass143the information in a wrapper however:144145.. click:example::146147    import urllib148149    class URL(object):150151        def __init__(self, url, fp):152            self.url = url153            self.fp = fp154155    def open_url(ctx, param, value):156        if value is not None:157            return URL(value, urllib.urlopen(value))158159    @click.command()160    @click.option('--url', callback=open_url)161    def cli(url):162        if url is not None:163            click.echo(f"{url.url}: {url.fp.code}")164165166Token Normalization167-------------------168169.. versionadded:: 2.0170171Starting with Click 2.0, it's possible to provide a function that is used172for normalizing tokens.  Tokens are option names, choice values, or command173values.  This can be used to implement case insensitive options, for174instance.175176In order to use this feature, the context needs to be passed a function that177performs the normalization of the token.  For instance, you could have a178function that converts the token to lowercase:179180.. click:example::181182    CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower())183184    @click.command(context_settings=CONTEXT_SETTINGS)185    @click.option('--name', default='Pete')186    def cli(name):187        click.echo(f"Name: {name}")188189And how it works on the command line:190191.. click:run::192193    invoke(cli, prog_name='cli', args=['--NAME=Pete'])194195Invoking Other Commands196-----------------------197198Sometimes, it might be interesting to invoke one command from another199command.  This is a pattern that is generally discouraged with Click, but200possible nonetheless.  For this, you can use the :func:`Context.invoke`201or :func:`Context.forward` methods.202203They work similarly, but the difference is that :func:`Context.invoke` merely204invokes another command with the arguments you provide as a caller,205whereas :func:`Context.forward` fills in the arguments from the current206command.  Both accept the command as the first argument and everything else207is passed onwards as you would expect.208209Example:210211.. click:example::212213    cli = click.Group()214215    @cli.command()216    @click.option('--count', default=1)217    def test(count):218        click.echo(f'Count: {count}')219220    @cli.command()221    @click.option('--count', default=1)222    @click.pass_context223    def dist(ctx, count):224        ctx.forward(test)225        ctx.invoke(test, count=42)226227And what it looks like:228229.. click:run::230231    invoke(cli, prog_name='cli', args=['dist'])232233234235.. _forwarding-unknown-options:236237Forwarding Unknown Options238--------------------------239240In some situations it is interesting to be able to accept all unknown241options for further manual processing.  Click can generally do that as of242Click 4.0, but it has some limitations that lie in the nature of the243problem.  The support for this is provided through a parser flag called244``ignore_unknown_options`` which will instruct the parser to collect all245unknown options and to put them to the leftover argument instead of246triggering a parsing error.247248This can generally be activated in two different ways:2492501.  It can be enabled on custom :class:`Command` subclasses by changing251    the :attr:`~Command.ignore_unknown_options` attribute.2522.  It can be enabled by changing the attribute of the same name on the253    context class (:attr:`Context.ignore_unknown_options`).  This is best254    changed through the ``context_settings`` dictionary on the command.255256For most situations the easiest solution is the second.  Once the behavior257is changed something needs to pick up those leftover options (which at258this point are considered arguments).  For this again you have two259options:2602611.  You can use :func:`pass_context` to get the context passed.  This will262    only work if in addition to :attr:`~Context.ignore_unknown_options`263    you also set :attr:`~Context.allow_extra_args` as otherwise the264    command will abort with an error that there are leftover arguments.265    If you go with this solution, the extra arguments will be collected in266    :attr:`Context.args`.2672.  You can attach an :func:`argument` with ``nargs`` set to `-1` which268    will eat up all leftover arguments.  In this case it's recommended to269    set the `type` to :data:`UNPROCESSED` to avoid any string processing270    on those arguments as otherwise they are forced into unicode strings271    automatically which is often not what you want.272273In the end you end up with something like this:274275.. click:example::276277    import sys278    from subprocess import call279280    @click.command(context_settings=dict(281        ignore_unknown_options=True,282    ))283    @click.option('-v', '--verbose', is_flag=True, help='Enables verbose mode')284    @click.argument('timeit_args', nargs=-1, type=click.UNPROCESSED)285    def cli(verbose, timeit_args):286        """A fake wrapper around Python's timeit."""287        cmdline = ['echo', 'python', '-mtimeit'] + list(timeit_args)288        if verbose:289            click.echo(f"Invoking: {' '.join(cmdline)}")290        call(cmdline)291292And what it looks like:293294.. click:run::295296    invoke(cli, prog_name='cli', args=['--help'])297    println()298    invoke(cli, prog_name='cli', args=['-n', '100', 'a = 1; b = 2; a * b'])299    println()300    invoke(cli, prog_name='cli', args=['-v', 'a = 1; b = 2; a * b'])301302As you can see the verbosity flag is handled by Click, everything else303ends up in the `timeit_args` variable for further processing which then304for instance, allows invoking a subprocess.  There are a few things that305are important to know about how this ignoring of unhandled flag happens:306307*   Unknown long options are generally ignored and not processed at all.308    So for instance if ``--foo=bar`` or ``--foo bar`` are passed they309    generally end up like that.  Note that because the parser cannot know310    if an option will accept an argument or not, the ``bar`` part might be311    handled as an argument.312*   Unknown short options might be partially handled and reassembled if313    necessary.  For instance in the above example there is an option314    called ``-v`` which enables verbose mode.  If the command would be315    ignored with ``-va`` then the ``-v`` part would be handled by Click316    (as it is known) and ``-a`` would end up in the leftover parameters317    for further processing.318*   Depending on what you plan on doing you might have some success by319    disabling interspersed arguments320    (:attr:`~Context.allow_interspersed_args`) which instructs the parser321    to not allow arguments and options to be mixed.  Depending on your322    situation this might improve your results.323324Generally though the combined handling of options and arguments from325your own commands and commands from another application are discouraged326and if you can avoid it, you should.  It's a much better idea to have327everything below a subcommand be forwarded to another application than to328handle some arguments yourself.329330331Managing Resources332------------------333334It can be useful to open a resource in a group, to be made available to335subcommands. Many types of resources need to be closed or otherwise336cleaned up after use. The standard way to do this in Python is by using337a context manager with the ``with`` statement.338339For example, the ``Repo`` class from :doc:`complex` might actually be340defined as a context manager:341342.. code-block:: python343344    class Repo:345        def __init__(self, home=None):346            self.home = os.path.abspath(home or ".")347            self.db = None348349        def __enter__(self):350            path = os.path.join(self.home, "repo.db")351            self.db = open_database(path)352            return self353354        def __exit__(self, exc_type, exc_value, tb):355            self.db.close()356357Ordinarily, it would be used with the ``with`` statement:358359.. code-block:: python360361    with Repo() as repo:362        repo.db.query(...)363364However, a ``with`` block in a group would exit and close the database365before it could be used by a subcommand.366367Instead, use the context's :meth:`~click.Context.with_resource` method368to enter the context manager and return the resource. When the group and369any subcommands finish, the context's resources are cleaned up.370371.. code-block:: python372373    @click.group()374    @click.option("--repo-home", default=".repo")375    @click.pass_context376    def cli(ctx, repo_home):377        ctx.obj = ctx.with_resource(Repo(repo_home))378379    @cli.command()380    @click.pass_obj381    def log(obj):382        # obj is the repo opened in the cli group383        for entry in obj.db.query(...):384            click.echo(entry)385386If the resource isn't a context manager, usually it can be wrapped in387one using something from :mod:`contextlib`. If that's not possible, use388the context's :meth:`~click.Context.call_on_close` method to register a389cleanup function.390391.. code-block:: python392393    @click.group()394    @click.option("--name", default="repo.db")395    @click.pass_context396    def cli(ctx, repo_home):397        ctx.obj = db = open_db(repo_home)398399        @ctx.call_on_close400        def close_db():401            db.record_use()402            db.save()403            db.close()404405406.. versionchanged:: 8.2 ``Context.call_on_close`` and context managers registered407    via ``Context.with_resource`` will be closed when the CLI exits. These were408    previously not called on exit.