commands.md
This file
Path
docs/commands.md
438 lines · 13.6 KiB · Markdown
Last changed by
Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e
History of this fileTake it
Move Commands doc from reST to MyST (#3243)Rowlando13before adoptione3c87be
lines 1–5why, one step back1# Advanced Groups and Context23```{currentmodule} click4```5Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e
lines 6–7why, one step back6In addition to the capabilities covered in the previous section, Groups have7more advanced capabilities that leverage the Context.Move Commands doc from reST to MyST (#3243)Rowlando13before adoptione3c87be
lines 8–438why, one step back89```{contents}10---11depth: 112local: true13---14```1516## Callback Invocation1718For a regular command, the callback is executed whenever the command runs.19If the script is the only command, it will always fire (unless a parameter20callback prevents it. This for instance happens if someone passes21`--help` to the script).2223For groups, the situation looks different. In this case, the callback fires24whenever a subcommand fires. What this means in practice is that an outer25command runs when an inner command runs:2627```{eval-rst}28.. click:example::2930 @click.group()31 @click.option('--debug/--no-debug', default=False)32 def cli(debug):33 click.echo(f"Debug mode is {'on' if debug else 'off'}")3435 @cli.command() # @cli, not @click!36 def sync():37 click.echo('Syncing')3839Here is what this looks like:4041.. click:run::4243 invoke(cli, prog_name='tool.py')44 println()45 invoke(cli, prog_name='tool.py', args=['--debug', 'sync'])46```4748## Nested Handling and Contexts4950As you can see from the earlier example, the basic command group accepts a51debug argument which is passed to its callback, but not to the sync52command itself. The sync command only accepts its own arguments.5354This allows tools to act completely independent of each other, but how55does one command talk to a nested one? The answer to this is the56{class}`Context`.5758Each time a command is invoked, a new context is created and linked with the59parent context. Normally, you can't see these contexts, but they are60there. Contexts are passed to parameter callbacks together with the61value automatically. Commands can also ask for the context to be passed62by marking themselves with the {func}`pass_context` decorator. In that63case, the context is passed as first argument.6465The context can also carry a program specified object that can be66used for the program's purposes. What this means is that you can build a67script like this:6869```{eval-rst}70.. click:example::7172 @click.group()73 @click.option('--debug/--no-debug', default=False)74 @click.pass_context75 def cli(ctx, debug):76 # ensure that ctx.obj exists and is a dict (in case `cli()` is called77 # by means other than the `if` block below)78 ctx.ensure_object(dict)7980 ctx.obj['DEBUG'] = debug8182 @cli.command()83 @click.pass_context84 def sync(ctx):85 click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}")8687 if __name__ == '__main__':88 cli(obj={})89```9091If the object is provided, each context will pass the object onwards to92its children, but at any level a context's object can be overridden. To93reach to a parent, `context.parent` can be used.9495In addition to that, instead of passing an object down, nothing stops the96application from modifying global state. For instance, you could just flip97a global `DEBUG` variable and be done with it.9899## Decorating Commands100101As you have seen in the earlier example, a decorator can change how a102command is invoked. What actually happens behind the scenes is that103callbacks are always invoked through the {meth}`Context.invoke` method104which automatically invokes a command correctly (by either passing the105context or not).106107This is very useful when you want to write custom decorators. For108instance, a common pattern would be to configure an object representing109state and then storing it on the context and then to use a custom110decorator to find the most recent object of this sort and pass it as first111argument.112113For instance, the {func}`pass_obj` decorator can be implemented like this:114115```{eval-rst}116.. click:example::117118 from functools import update_wrapper119120 def pass_obj(f):121 @click.pass_context122 def new_func(ctx, *args, **kwargs):123 return ctx.invoke(f, ctx.obj, *args, **kwargs)124 return update_wrapper(new_func, f)125```126127The {meth}`Context.invoke` command will automatically invoke the function128in the correct way, so the function will either be called with`f(ctx,129obj)` or `f(obj)` depending on whether or not it itself is decorated with130{func}`pass_context`.131132This is a very powerful concept that can be used to build very complex133nested applications; see {ref}`complex-guide` for more information.134135(command-chaining)=136137## Command Chaining138139It is useful to invoke more than one subcommand in one call. For example,140`my-app validate build upload` would invoke `validate`, then `build`, then141`upload`. To implement this, pass `chain=True` when creating a group.142143```{eval-rst}144.. click:example::145146 @click.group(chain=True)147 def cli():148 pass149150 @cli.command('validate')151 def validate():152 click.echo('validate')153154 @cli.command('build')155 def build():156 click.echo('build')157158You can invoke it like this:159160.. click:run::161162 invoke(cli, prog_name='my-app', args=['validate', 'build'])163```164165When using chaining, there are a few restrictions:166167- Only the last command may use `nargs=-1` on an argument, otherwise the168 parser will not be able to find further commands.169- It is not possible to nest groups below a chain group.170- On the command line, options must be specified before arguments for each171 command in the chain.172- The {attr}`Context.invoked_subcommand` attribute will be `'*'` because the173 parser doesn't know the full list of commands that will run yet.174175(command-pipelines)=176177## Command Pipelines178179When using chaining, a common pattern is to have each command process the180result of the previous command.181182A straightforward way to do this is to use {func}`make_pass_decorator` to pass183a context object to each command, and store and read the data on that object.184185```{eval-rst}186.. click:example::187188 pass_ns = click.make_pass_decorator(dict, ensure=True)189190 @click.group(chain=True)191 @click.argument("name")192 @pass_ns193 def cli(ns, name):194 ns["name"] = name195196 @cli.command197 @pass_ns198 def lower(ns):199 ns["name"] = ns["name"].lower()200201 @cli.command202 @pass_ns203 def show(ns):204 click.echo(ns["name"])205206.. click:run::207208 invoke(cli, prog_name="process", args=["Click", "show", "lower", "show"])209```210211Another way to do this is to collect data returned by each command, then process212it at the end of the chain. Use the group's {meth}`~Group.result_callback`213decorator to register a function that is called after the chain is finished. It214is passed the list of return values as well as any parameters registered on the215group.216217A command can return anything, including a function. Here's an example of that,218where each subcommand creates a function that processes the input, then the219result callback calls each function. The command takes a file, processes each220line, then outputs it. If no subcommands are given, it outputs the contents221of the file unchanged.222223```python224@click.group(chain=True, invoke_without_command=True)225@click.argument("fin", type=click.File("r"))226def cli(fin):227 pass228229@cli.result_callback()230def process_pipeline(processors, fin):231 iterator = (x.rstrip("\r\n") for x in input)232233 for processor in processors:234 iterator = processor(iterator)235236 for item in iterator:237 click.echo(item)238239@cli.command("upper")240def make_uppercase():241 def processor(iterator):242 for line in iterator:243 yield line.upper()244 return processor245246@cli.command("lower")247def make_lowercase():248 def processor(iterator):249 for line in iterator:250 yield line.lower()251 return processor252253@cli.command("strip")254def make_strip():255 def processor(iterator):256 for line in iterator:257 yield line.strip()258 return processor259```260261That's a lot in one go, so let's go through it step by step.2622631. The first thing is to make a {func}`group` that is chainable. In264 addition to that we also instruct Click to invoke even if no265 subcommand is defined. If this would not be done, then invoking an266 empty pipeline would produce the help page instead of running the267 result callbacks.2682. The next thing we do is to register a result callback on our group.269 This callback will be invoked with an argument which is the list of270 all return values of all subcommands and then the same keyword271 parameters as our group itself. This means we can access the input272 file easily there without having to use the context object.2733. In this result callback we create an iterator of all the lines in the274 input file and then pass this iterator through all the returned275 callbacks from all subcommands and finally we print all lines to276 stdout.277278After that point we can register as many subcommands as we want and each279subcommand can return a processor function to modify the stream of lines.280281One important thing of note is that Click shuts down the context after282each callback has been run. This means that for instance file types283cannot be accessed in the `processor` functions as the files will already284be closed there. This limitation is unlikely to change because it would285make resource handling much more complicated. For such it's recommended286to not use the file type and manually open the file through287{func}`open_file`.288289For a more complex example that also improves upon handling of the pipelines,290see the [imagepipe example](https://github.com/pallets/click/tree/main/examples/imagepipe)291in the Click repository. It implements a pipeline based image editing tool292that has a nice internal structure.293294## Overriding Defaults295296By default, the default value for a parameter is pulled from the297`default` flag that is provided when it's defined, but that's not the298only place defaults can be loaded from. The other place is the299{attr}`Context.default_map` (a dictionary) on the context. This allows300defaults to be loaded from a configuration file to override the regular301defaults.302303This is useful if you plug in some commands from another package but304you're not satisfied with the defaults.305306The default map can be nested arbitrarily for each subcommand:307308```python309310 default_map = {311 "debug": True, # default for a top level option312 "runserver": {"port": 5000} # default for a subcommand313 }314```315316The default map can be provided when the script is invoked, or317overridden at any point by commands. For instance, a top-level command318could load the defaults from a configuration file.319320Example usage:321322```{eval-rst}323.. click:example::324325 import click326327 @click.group()328 def cli():329 pass330331 @cli.command()332 @click.option('--port', default=8000)333 def runserver(port):334 click.echo(f"Serving on http://127.0.0.1:{port}/")335336 if __name__ == '__main__':337 cli(default_map={338 'runserver': {339 'port': 5000340 }341 })342343And in action:344345.. click:run::346347 invoke(cli, prog_name='cli', args=['runserver'], default_map={348 'runserver': {349 'port': 5000350 }351 })352```353354## Context Defaults355356```{versionadded} 2.0357```358359Starting with Click 2.0 you can override defaults for contexts not just360when calling your script, but also in the decorator that declares a361command. For instance given the previous example which defines a custom362`default_map` this can also be accomplished in the decorator now.363364This example does the same as the previous example:365366```{eval-rst}367.. click:example::368369 import click370371 CONTEXT_SETTINGS = dict(372 default_map={'runserver': {'port': 5000}}373 )374375 @click.group(context_settings=CONTEXT_SETTINGS)376 def cli():377 pass378379 @cli.command()380 @click.option('--port', default=8000)381 def runserver(port):382 click.echo(f"Serving on http://127.0.0.1:{port}/")383384 if __name__ == '__main__':385 cli()386387And again the example in action:388389.. click:run::390391 invoke(cli, prog_name='cli', args=['runserver'])392```393394## Command Return Values395396```{versionadded} 3.0397```398399One of the new introductions in Click 3.0 is the full support for return400values from command callbacks. This enables a whole range of features401that were previously hard to implement.402403In essence any command callback can now return a value. This return value404is bubbled to certain receivers. One usecase for this has already been405show in the example of {ref}`command-chaining` where it has been406demonstrated that chained groups can have callbacks that process407all return values.408409When working with command return values in Click, this is what you need to410know:411412- The return value of a command callback is generally returned from the413 {meth}`Command.invoke` method. The exception to this rule has to414 do with {class}`Group`s:415416 - In a group the return value is generally the return value of the417 subcommand invoked. The only exception to this rule is that the418 return value is the return value of the group callback if it's419 invoked without arguments and `invoke_without_command` is enabled.420 - If a group is set up for chaining then the return value is a list421 of all subcommands' results.422 - Return values of groups can be processed through a423 {attr}`Group.result_callback`. This is invoked with the424 list of all return values in chain mode, or the single return425 value in case of non chained commands.426427- The return value is bubbled through from the {meth}`Context.invoke`428 and {meth}`Context.forward` methods. This is useful in situations429 where you internally want to call into another command.430431- Click does not have any hard requirements for the return values and432 does not use them itself. This allows return values to be used for433 custom decorators or workflows (like in the command chaining434 example).435436- When a Click script is invoked as command line application (through437 {meth}`Command.main`) the return value is ignored unless the438 `standalone_mode` is disabled in which case it's bubbled through.