commands.rst
This file
Path
docs/commands.rst
569 lines · 18.3 KiB
Last changed by
switch to flit build backend (#2543)David Lordbefore adoption3fcf338
History of this fileTake 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 example, ``my-app validate build upload`` would invoke ``validate``,289then ``build``, then ``upload``. To implement this in Click, pass ``chain=True``290when creating a group.291292.. click:example::293294 @click.group(chain=True)295 def cli():296 pass297298299 @cli.command('sdist')300 def sdist():301 click.echo('sdist called')302303304 @cli.command('bdist_wheel')305 def bdist_wheel():306 click.echo('bdist_wheel called')307308Now you can invoke it like this:309310.. click:run::311312 invoke(cli, prog_name='setup.py', args=['sdist', 'bdist_wheel'])313314When using multi command chaining you can only have one command (the last)315use ``nargs=-1`` on an argument. It is also not possible to nest multi316commands below chained multicommands. Other than that there are no317restrictions on how they work. They can accept options and arguments as318normal. The order between options and arguments is limited for chained319commands. Currently only ``--options argument`` order is allowed.320321Another note: the :attr:`Context.invoked_subcommand` attribute is a bit322useless for multi commands as it will give ``'*'`` as value if more than323one command is invoked. This is necessary because the handling of324subcommands happens one after another so the exact subcommands that will325be handled are not yet available when the callback fires.326327.. note::328329 It is currently not possible for chain commands to be nested. This330 will be fixed in future versions of Click.331332333Multi Command Pipelines334-----------------------335336.. versionadded:: 3.0337338A very common usecase of multi command chaining is to have one command339process the result of the previous command. There are various ways in340which this can be facilitated. The most obvious way is to store a value341on the context object and process it from function to function. This342works by decorating a function with :func:`pass_context` after which the343context object is provided and a subcommand can store its data there.344345Another way to accomplish this is to setup pipelines by returning346processing functions. Think of it like this: when a subcommand gets347invoked it processes all of its parameters and comes up with a plan of348how to do its processing. At that point it then returns a processing349function and returns.350351Where do the returned functions go? The chained multicommand can register352a callback with :meth:`MultiCommand.result_callback` that goes over all353these functions and then invoke them.354355To make this a bit more concrete consider this example:356357.. click:example::358359 @click.group(chain=True, invoke_without_command=True)360 @click.option('-i', '--input', type=click.File('r'))361 def cli(input):362 pass363364 @cli.result_callback()365 def process_pipeline(processors, input):366 iterator = (x.rstrip('\r\n') for x in input)367 for processor in processors:368 iterator = processor(iterator)369 for item in iterator:370 click.echo(item)371372 @cli.command('uppercase')373 def make_uppercase():374 def processor(iterator):375 for line in iterator:376 yield line.upper()377 return processor378379 @cli.command('lowercase')380 def make_lowercase():381 def processor(iterator):382 for line in iterator:383 yield line.lower()384 return processor385386 @cli.command('strip')387 def make_strip():388 def processor(iterator):389 for line in iterator:390 yield line.strip()391 return processor392393That's a lot in one go, so let's go through it step by step.3943951. The first thing is to make a :func:`group` that is chainable. In396 addition to that we also instruct Click to invoke even if no397 subcommand is defined. If this would not be done, then invoking an398 empty pipeline would produce the help page instead of running the399 result callbacks.4002. The next thing we do is to register a result callback on our group.401 This callback will be invoked with an argument which is the list of402 all return values of all subcommands and then the same keyword403 parameters as our group itself. This means we can access the input404 file easily there without having to use the context object.4053. In this result callback we create an iterator of all the lines in the406 input file and then pass this iterator through all the returned407 callbacks from all subcommands and finally we print all lines to408 stdout.409410After that point we can register as many subcommands as we want and each411subcommand can return a processor function to modify the stream of lines.412413One important thing of note is that Click shuts down the context after414each callback has been run. This means that for instance file types415cannot be accessed in the `processor` functions as the files will already416be closed there. This limitation is unlikely to change because it would417make resource handling much more complicated. For such it's recommended418to not use the file type and manually open the file through419:func:`open_file`.420421For a more complex example that also improves upon handling of the422pipelines have a look at the `imagepipe multi command chaining demo423<https://github.com/pallets/click/tree/main/examples/imagepipe>`__ in424the Click repository. It implements a pipeline based image editing tool425that has a nice internal structure for the pipelines.426427428Overriding Defaults429-------------------430431By default, the default value for a parameter is pulled from the432``default`` flag that is provided when it's defined, but that's not the433only place defaults can be loaded from. The other place is the434:attr:`Context.default_map` (a dictionary) on the context. This allows435defaults to be loaded from a configuration file to override the regular436defaults.437438This is useful if you plug in some commands from another package but439you're not satisfied with the defaults.440441The default map can be nested arbitrarily for each subcommand:442443.. code-block:: python444445 default_map = {446 "debug": True, # default for a top level option447 "runserver": {"port": 5000} # default for a subcommand448 }449450The default map can be provided when the script is invoked, or451overridden at any point by commands. For instance, a top-level command452could load the defaults from a configuration file.453454Example usage:455456.. click:example::457458 import click459460 @click.group()461 def cli():462 pass463464 @cli.command()465 @click.option('--port', default=8000)466 def runserver(port):467 click.echo(f"Serving on http://127.0.0.1:{port}/")468469 if __name__ == '__main__':470 cli(default_map={471 'runserver': {472 'port': 5000473 }474 })475476And in action:477478.. click:run::479480 invoke(cli, prog_name='cli', args=['runserver'], default_map={481 'runserver': {482 'port': 5000483 }484 })485486Context Defaults487----------------488489.. versionadded:: 2.0490491Starting with Click 2.0 you can override defaults for contexts not just492when calling your script, but also in the decorator that declares a493command. For instance given the previous example which defines a custom494``default_map`` this can also be accomplished in the decorator now.495496This example does the same as the previous example:497498.. click:example::499500 import click501502 CONTEXT_SETTINGS = dict(503 default_map={'runserver': {'port': 5000}}504 )505506 @click.group(context_settings=CONTEXT_SETTINGS)507 def cli():508 pass509510 @cli.command()511 @click.option('--port', default=8000)512 def runserver(port):513 click.echo(f"Serving on http://127.0.0.1:{port}/")514515 if __name__ == '__main__':516 cli()517518And again the example in action:519520.. click:run::521522 invoke(cli, prog_name='cli', args=['runserver'])523524525Command Return Values526---------------------527528.. versionadded:: 3.0529530One of the new introductions in Click 3.0 is the full support for return531values from command callbacks. This enables a whole range of features532that were previously hard to implement.533534In essence any command callback can now return a value. This return value535is bubbled to certain receivers. One usecase for this has already been536show in the example of :ref:`multi-command-chaining` where it has been537demonstrated that chained multi commands can have callbacks that process538all return values.539540When working with command return values in Click, this is what you need to541know:542543- The return value of a command callback is generally returned from the544 :meth:`BaseCommand.invoke` method. The exception to this rule has to545 do with :class:`Group`\s:546547 * In a group the return value is generally the return value of the548 subcommand invoked. The only exception to this rule is that the549 return value is the return value of the group callback if it's550 invoked without arguments and `invoke_without_command` is enabled.551 * If a group is set up for chaining then the return value is a list552 of all subcommands' results.553 * Return values of groups can be processed through a554 :attr:`MultiCommand.result_callback`. This is invoked with the555 list of all return values in chain mode, or the single return556 value in case of non chained commands.557558- The return value is bubbled through from the :meth:`Context.invoke`559 and :meth:`Context.forward` methods. This is useful in situations560 where you internally want to call into another command.561562- Click does not have any hard requirements for the return values and563 does not use them itself. This allows return values to be used for564 custom decorators or workflows (like in the multi command chaining565 example).566567- When a Click script is invoked as command line application (through568 :meth:`BaseCommand.main`) the return value is ignored unless the569 `standalone_mode` is disabled in which case it's bubbled through.