Skip to content
Myr

commands.rst

This file

Path

docs/commands.rst

571 lines · 18.5 KiB

Last changed by

Merge remote-tracking branch 'origin/8.0.x'David Lordbefore adoption8a04bb0

History of this file

Take it

1Commands and Groups2===================34.. currentmodule:: click56The most important feature of Click is the concept of arbitrarily nesting7command line utilities.  This is implemented through the :class:`Command`8and :class:`Group` (actually :class:`MultiCommand`).910Callback Invocation11-------------------1213For a regular command, the callback is executed whenever the command runs.14If the script is the only command, it will always fire (unless a parameter15callback prevents it.  This for instance happens if someone passes16``--help`` to the script).1718For groups and multi commands, the situation looks different.  In this case,19the callback fires whenever a subcommand fires (unless this behavior is20changed).  What this means in practice is that an outer command runs21when an inner command runs:2223.. click:example::2425    @click.group()26    @click.option('--debug/--no-debug', default=False)27    def cli(debug):28        click.echo(f"Debug mode is {'on' if debug else 'off'}")2930    @cli.command()  # @cli, not @click!31    def sync():32        click.echo('Syncing')3334Here is what this looks like:3536.. click:run::3738    invoke(cli, prog_name='tool.py')39    println()40    invoke(cli, prog_name='tool.py', args=['--debug', 'sync'])4142Passing Parameters43------------------4445Click strictly separates parameters between commands and subcommands. What this46means is that options and arguments for a specific command have to be specified47*after* the command name itself, but *before* any other command names.4849This behavior is already observable with the predefined ``--help`` option.50Suppose we have a program called ``tool.py``, containing a subcommand called51``sub``.5253- ``tool.py --help`` will return the help for the whole program (listing54  subcommands).5556- ``tool.py sub --help`` will return the help for the ``sub`` subcommand.5758- But ``tool.py --help sub`` will treat ``--help`` as an argument for the main59  program. Click then invokes the callback for ``--help``, which prints the60  help and aborts the program before click can process the subcommand.6162Nested Handling and Contexts63----------------------------6465As you can see from the earlier example, the basic command group accepts a66debug argument which is passed to its callback, but not to the sync67command itself.  The sync command only accepts its own arguments.6869This allows tools to act completely independent of each other, but how70does one command talk to a nested one?  The answer to this is the71:class:`Context`.7273Each time a command is invoked, a new context is created and linked with the74parent context.  Normally, you can't see these contexts, but they are75there.  Contexts are passed to parameter callbacks together with the76value automatically.  Commands can also ask for the context to be passed77by marking themselves with the :func:`pass_context` decorator.  In that78case, the context is passed as first argument.7980The context can also carry a program specified object that can be81used for the program's purposes.  What this means is that you can build a82script like this:8384.. click:example::8586    @click.group()87    @click.option('--debug/--no-debug', default=False)88    @click.pass_context89    def cli(ctx, debug):90        # ensure that ctx.obj exists and is a dict (in case `cli()` is called91        # by means other than the `if` block below)92        ctx.ensure_object(dict)9394        ctx.obj['DEBUG'] = debug9596    @cli.command()97    @click.pass_context98    def sync(ctx):99        click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}")100101    if __name__ == '__main__':102        cli(obj={})103104If the object is provided, each context will pass the object onwards to105its children, but at any level a context's object can be overridden.  To106reach to a parent, ``context.parent`` can be used.107108In addition to that, instead of passing an object down, nothing stops the109application from modifying global state.  For instance, you could just flip110a global ``DEBUG`` variable and be done with it.111112Decorating Commands113-------------------114115As you have seen in the earlier example, a decorator can change how a116command is invoked.  What actually happens behind the scenes is that117callbacks are always invoked through the :meth:`Context.invoke` method118which automatically invokes a command correctly (by either passing the119context or not).120121This is very useful when you want to write custom decorators.  For122instance, a common pattern would be to configure an object representing123state and then storing it on the context and then to use a custom124decorator to find the most recent object of this sort and pass it as first125argument.126127For instance, the :func:`pass_obj` decorator can be implemented like this:128129.. click:example::130131    from functools import update_wrapper132133    def pass_obj(f):134        @click.pass_context135        def new_func(ctx, *args, **kwargs):136            return ctx.invoke(f, ctx.obj, *args, **kwargs)137        return update_wrapper(new_func, f)138139The :meth:`Context.invoke` command will automatically invoke the function140in the correct way, so the function will either be called with ``f(ctx,141obj)`` or ``f(obj)`` depending on whether or not it itself is decorated with142:func:`pass_context`.143144This is a very powerful concept that can be used to build very complex145nested applications; see :ref:`complex-guide` for more information.146147148Group Invocation Without Command149--------------------------------150151By default, a group or multi command is not invoked unless a subcommand is152passed.  In fact, not providing a command automatically passes ``--help``153by default.  This behavior can be changed by passing154``invoke_without_command=True`` to a group.  In that case, the callback is155always invoked instead of showing the help page.  The context object also156includes information about whether or not the invocation would go to a157subcommand.158159Example:160161.. click:example::162163    @click.group(invoke_without_command=True)164    @click.pass_context165    def cli(ctx):166        if ctx.invoked_subcommand is None:167            click.echo('I was invoked without subcommand')168        else:169            click.echo(f"I am about to invoke {ctx.invoked_subcommand}")170171    @cli.command()172    def sync():173        click.echo('The subcommand')174175And how it works in practice:176177.. click:run::178179    invoke(cli, prog_name='tool', args=[])180    invoke(cli, prog_name='tool', args=['sync'])181182.. _custom-multi-commands:183184Custom Multi Commands185---------------------186187In addition to using :func:`click.group`, you can also build your own188custom multi commands.  This is useful when you want to support commands189being loaded lazily from plugins.190191A custom multi command just needs to implement a list and load method:192193.. click:example::194195    import click196    import os197198    plugin_folder = os.path.join(os.path.dirname(__file__), 'commands')199200    class MyCLI(click.MultiCommand):201202        def list_commands(self, ctx):203            rv = []204            for filename in os.listdir(plugin_folder):205                if filename.endswith('.py') and filename != '__init__.py':206                    rv.append(filename[:-3])207            rv.sort()208            return rv209210        def get_command(self, ctx, name):211            ns = {}212            fn = os.path.join(plugin_folder, name + '.py')213            with open(fn) as f:214                code = compile(f.read(), fn, 'exec')215                eval(code, ns, ns)216            return ns['cli']217218    cli = MyCLI(help='This tool\'s subcommands are loaded from a '219                'plugin folder dynamically.')220221    if __name__ == '__main__':222        cli()223224These custom classes can also be used with decorators:225226.. click:example::227228    @click.command(cls=MyCLI)229    def cli():230        pass231232Merging Multi Commands233----------------------234235In addition to implementing custom multi commands, it can also be236interesting to merge multiple together into one script.  While this is237generally not as recommended as it nests one below the other, the merging238approach can be useful in some circumstances for a nicer shell experience.239240The default implementation for such a merging system is the241:class:`CommandCollection` class.  It accepts a list of other multi242commands and makes the commands available on the same level.243244Example usage:245246.. click:example::247248    import click249250    @click.group()251    def cli1():252        pass253254    @cli1.command()255    def cmd1():256        """Command on cli1"""257258    @click.group()259    def cli2():260        pass261262    @cli2.command()263    def cmd2():264        """Command on cli2"""265266    cli = click.CommandCollection(sources=[cli1, cli2])267268    if __name__ == '__main__':269        cli()270271And what it looks like:272273.. click:run::274275    invoke(cli, prog_name='cli', args=['--help'])276277In case a command exists in more than one source, the first source wins.278279280.. _multi-command-chaining:281282Multi Command Chaining283----------------------284285.. versionadded:: 3.0286287Sometimes it is useful to be allowed to invoke more than one subcommand in288one go.  For instance if you have installed a setuptools package before289you might be familiar with the ``setup.py sdist bdist_wheel upload``290command chain which invokes ``sdist`` before ``bdist_wheel`` before291``upload``.  Starting with Click 3.0 this is very simple to implement.292All you have to do is to pass ``chain=True`` to your multicommand:293294.. click:example::295296    @click.group(chain=True)297    def cli():298        pass299300301    @cli.command('sdist')302    def sdist():303        click.echo('sdist called')304305306    @cli.command('bdist_wheel')307    def bdist_wheel():308        click.echo('bdist_wheel called')309310Now you can invoke it like this:311312.. click:run::313314    invoke(cli, prog_name='setup.py', args=['sdist', 'bdist_wheel'])315316When using multi command chaining you can only have one command (the last)317use ``nargs=-1`` on an argument.  It is also not possible to nest multi318commands below chained multicommands.  Other than that there are no319restrictions on how they work.  They can accept options and arguments as320normal. The order between options and arguments is limited for chained321commands. Currently only ``--options argument`` order is allowed.322323Another note: the :attr:`Context.invoked_subcommand` attribute is a bit324useless for multi commands as it will give ``'*'`` as value if more than325one command is invoked.  This is necessary because the handling of326subcommands happens one after another so the exact subcommands that will327be handled are not yet available when the callback fires.328329.. note::330331    It is currently not possible for chain commands to be nested.  This332    will be fixed in future versions of Click.333334335Multi Command Pipelines336-----------------------337338.. versionadded:: 3.0339340A very common usecase of multi command chaining is to have one command341process the result of the previous command.  There are various ways in342which this can be facilitated.  The most obvious way is to store a value343on the context object and process it from function to function.  This344works by decorating a function with :func:`pass_context` after which the345context object is provided and a subcommand can store its data there.346347Another way to accomplish this is to setup pipelines by returning348processing functions.  Think of it like this: when a subcommand gets349invoked it processes all of its parameters and comes up with a plan of350how to do its processing.  At that point it then returns a processing351function and returns.352353Where do the returned functions go?  The chained multicommand can register354a callback with :meth:`MultiCommand.result_callback` that goes over all355these functions and then invoke them.356357To make this a bit more concrete consider this example:358359.. click:example::360361    @click.group(chain=True, invoke_without_command=True)362    @click.option('-i', '--input', type=click.File('r'))363    def cli(input):364        pass365366    @cli.result_callback()367    def process_pipeline(processors, input):368        iterator = (x.rstrip('\r\n') for x in input)369        for processor in processors:370            iterator = processor(iterator)371        for item in iterator:372            click.echo(item)373374    @cli.command('uppercase')375    def make_uppercase():376        def processor(iterator):377            for line in iterator:378                yield line.upper()379        return processor380381    @cli.command('lowercase')382    def make_lowercase():383        def processor(iterator):384            for line in iterator:385                yield line.lower()386        return processor387388    @cli.command('strip')389    def make_strip():390        def processor(iterator):391            for line in iterator:392                yield line.strip()393        return processor394395That's a lot in one go, so let's go through it step by step.3963971.  The first thing is to make a :func:`group` that is chainable.  In398    addition to that we also instruct Click to invoke even if no399    subcommand is defined.  If this would not be done, then invoking an400    empty pipeline would produce the help page instead of running the401    result callbacks.4022.  The next thing we do is to register a result callback on our group.403    This callback will be invoked with an argument which is the list of404    all return values of all subcommands and then the same keyword405    parameters as our group itself.  This means we can access the input406    file easily there without having to use the context object.4073.  In this result callback we create an iterator of all the lines in the408    input file and then pass this iterator through all the returned409    callbacks from all subcommands and finally we print all lines to410    stdout.411412After that point we can register as many subcommands as we want and each413subcommand can return a processor function to modify the stream of lines.414415One important thing of note is that Click shuts down the context after416each callback has been run.  This means that for instance file types417cannot be accessed in the `processor` functions as the files will already418be closed there.  This limitation is unlikely to change because it would419make resource handling much more complicated.  For such it's recommended420to not use the file type and manually open the file through421:func:`open_file`.422423For a more complex example that also improves upon handling of the424pipelines have a look at the `imagepipe multi command chaining demo425<https://github.com/pallets/click/tree/main/examples/imagepipe>`__ in426the Click repository.  It implements a pipeline based image editing tool427that has a nice internal structure for the pipelines.428429430Overriding Defaults431-------------------432433By default, the default value for a parameter is pulled from the434``default`` flag that is provided when it's defined, but that's not the435only place defaults can be loaded from.  The other place is the436:attr:`Context.default_map` (a dictionary) on the context.  This allows437defaults to be loaded from a configuration file to override the regular438defaults.439440This is useful if you plug in some commands from another package but441you're not satisfied with the defaults.442443The default map can be nested arbitrarily for each subcommand:444445.. code-block:: python446447    default_map = {448        "debug": True,  # default for a top level option449        "runserver": {"port": 5000}  # default for a subcommand450    }451452The default map can be provided when the script is invoked, or453overridden at any point by commands. For instance, a top-level command454could load the defaults from a configuration file.455456Example usage:457458.. click:example::459460    import click461462    @click.group()463    def cli():464        pass465466    @cli.command()467    @click.option('--port', default=8000)468    def runserver(port):469        click.echo(f"Serving on http://127.0.0.1:{port}/")470471    if __name__ == '__main__':472        cli(default_map={473            'runserver': {474                'port': 5000475            }476        })477478And in action:479480.. click:run::481482    invoke(cli, prog_name='cli', args=['runserver'], default_map={483        'runserver': {484            'port': 5000485        }486    })487488Context Defaults489----------------490491.. versionadded:: 2.0492493Starting with Click 2.0 you can override defaults for contexts not just494when calling your script, but also in the decorator that declares a495command.  For instance given the previous example which defines a custom496``default_map`` this can also be accomplished in the decorator now.497498This example does the same as the previous example:499500.. click:example::501502    import click503504    CONTEXT_SETTINGS = dict(505        default_map={'runserver': {'port': 5000}}506    )507508    @click.group(context_settings=CONTEXT_SETTINGS)509    def cli():510        pass511512    @cli.command()513    @click.option('--port', default=8000)514    def runserver(port):515        click.echo(f"Serving on http://127.0.0.1:{port}/")516517    if __name__ == '__main__':518        cli()519520And again the example in action:521522.. click:run::523524    invoke(cli, prog_name='cli', args=['runserver'])525526527Command Return Values528---------------------529530.. versionadded:: 3.0531532One of the new introductions in Click 3.0 is the full support for return533values from command callbacks.  This enables a whole range of features534that were previously hard to implement.535536In essence any command callback can now return a value.  This return value537is bubbled to certain receivers.  One usecase for this has already been538show in the example of :ref:`multi-command-chaining` where it has been539demonstrated that chained multi commands can have callbacks that process540all return values.541542When working with command return values in Click, this is what you need to543know:544545-   The return value of a command callback is generally returned from the546    :meth:`BaseCommand.invoke` method.  The exception to this rule has to547    do with :class:`Group`\s:548549    *   In a group the return value is generally the return value of the550        subcommand invoked.  The only exception to this rule is that the551        return value is the return value of the group callback if it's552        invoked without arguments and `invoke_without_command` is enabled.553    *   If a group is set up for chaining then the return value is a list554        of all subcommands' results.555    *   Return values of groups can be processed through a556        :attr:`MultiCommand.result_callback`.  This is invoked with the557        list of all return values in chain mode, or the single return558        value in case of non chained commands.559560-   The return value is bubbled through from the :meth:`Context.invoke`561    and :meth:`Context.forward` methods.  This is useful in situations562    where you internally want to call into another command.563564-   Click does not have any hard requirements for the return values and565    does not use them itself.  This allows return values to be used for566    custom decorators or workflows (like in the multi command chaining567    example).568569-   When a Click script is invoked as command line application (through570    :meth:`BaseCommand.main`) the return value is ignored unless the571    `standalone_mode` is disabled in which case it's bubbled through.