commands.rst
This file
Path
docs/commands.rst
428 lines · 13.9 KiB
Last changed by
Rewrite Commands and Groups docs. (#2838)Rowlando13before adoption0bf333e
History of this fileTake it
The walk stopped after 200 commits: lines older than c96545f point at it.
Rewrite Commands and Groups docs. (#2838)Rowlando13before adoption0bf333e
lines 1–2why, one step back1Advanced Groups and Context2=============================Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
lines 3–5why, one step back34.. currentmodule:: click5Rewrite Commands and Groups docs. (#2838)Rowlando13before adoption0bf333e
line 6why, one step back6In addition to the capabilities covered in the previous section, Groups have more advanced capabilities that leverage the Context.Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
line 7why, one step back7Rewrite Commands and Groups docs. (#2838)Rowlando13before adoption0bf333e
lines 8–10why, one step back8.. contents::9 :depth: 110 :local:deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
line 11why, one step back11Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
lines 12–19why, one step back12Callback Invocation13-------------------1415For a regular command, the callback is executed whenever the command runs.16If the script is the only command, it will always fire (unless a parameter17callback prevents it. This for instance happens if someone passes18``--help`` to the script).19deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
lines 20–22why, one step back20For groups, the situation looks different. In this case, the callback fires21whenever a subcommand fires. What this means in practice is that an outer22command runs when an inner command runs:Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
lines 23–127why, one step back2324.. click:example::2526 @click.group()27 @click.option('--debug/--no-debug', default=False)28 def cli(debug):29 click.echo(f"Debug mode is {'on' if debug else 'off'}")3031 @cli.command() # @cli, not @click!32 def sync():33 click.echo('Syncing')3435Here is what this looks like:3637.. click:run::3839 invoke(cli, prog_name='tool.py')40 println()41 invoke(cli, prog_name='tool.py', args=['--debug', 'sync'])4243Nested Handling and Contexts44----------------------------4546As you can see from the earlier example, the basic command group accepts a47debug argument which is passed to its callback, but not to the sync48command itself. The sync command only accepts its own arguments.4950This allows tools to act completely independent of each other, but how51does one command talk to a nested one? The answer to this is the52:class:`Context`.5354Each time a command is invoked, a new context is created and linked with the55parent context. Normally, you can't see these contexts, but they are56there. Contexts are passed to parameter callbacks together with the57value automatically. Commands can also ask for the context to be passed58by marking themselves with the :func:`pass_context` decorator. In that59case, the context is passed as first argument.6061The context can also carry a program specified object that can be62used for the program's purposes. What this means is that you can build a63script like this:6465.. click:example::6667 @click.group()68 @click.option('--debug/--no-debug', default=False)69 @click.pass_context70 def cli(ctx, debug):71 # ensure that ctx.obj exists and is a dict (in case `cli()` is called72 # by means other than the `if` block below)73 ctx.ensure_object(dict)7475 ctx.obj['DEBUG'] = debug7677 @cli.command()78 @click.pass_context79 def sync(ctx):80 click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}")8182 if __name__ == '__main__':83 cli(obj={})8485If the object is provided, each context will pass the object onwards to86its children, but at any level a context's object can be overridden. To87reach to a parent, ``context.parent`` can be used.8889In addition to that, instead of passing an object down, nothing stops the90application from modifying global state. For instance, you could just flip91a global ``DEBUG`` variable and be done with it.9293Decorating Commands94-------------------9596As you have seen in the earlier example, a decorator can change how a97command is invoked. What actually happens behind the scenes is that98callbacks are always invoked through the :meth:`Context.invoke` method99which automatically invokes a command correctly (by either passing the100context or not).101102This is very useful when you want to write custom decorators. For103instance, a common pattern would be to configure an object representing104state and then storing it on the context and then to use a custom105decorator to find the most recent object of this sort and pass it as first106argument.107108For instance, the :func:`pass_obj` decorator can be implemented like this:109110.. click:example::111112 from functools import update_wrapper113114 def pass_obj(f):115 @click.pass_context116 def new_func(ctx, *args, **kwargs):117 return ctx.invoke(f, ctx.obj, *args, **kwargs)118 return update_wrapper(new_func, f)119120The :meth:`Context.invoke` command will automatically invoke the function121in the correct way, so the function will either be called with ``f(ctx,122obj)`` or ``f(obj)`` depending on whether or not it itself is decorated with123:func:`pass_context`.124125This is a very powerful concept that can be used to build very complex126nested applications; see :ref:`complex-guide` for more information.127deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
line 128why, one step back128.. _command-chaining:Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
line 129why, one step back129deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
lines 130–131why, one step back130Command Chaining131----------------Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
line 132why, one step back132deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
lines 133–135why, one step back133It is useful to invoke more than one subcommand in one call. For example,134``my-app validate build upload`` would invoke ``validate``, then ``build``, then135``upload``. To implement this, pass ``chain=True`` when creating a group.Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
lines 136–138why, one step back136137.. click:example::138deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
lines 139–140why, one step back139 @click.group(chain=True)140 def cli():Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
lines 141–142why, one step back141 pass142deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
lines 143–145why, one step back143 @cli.command('validate')144 def validate():145 click.echo('validate')Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
line 146why, one step back146deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
lines 147–149why, one step back147 @cli.command('build')148 def build():149 click.echo('build')Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
line 150why, one step back150deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
line 151why, one step back151You can invoke it like this:Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
lines 152–154why, one step back152153.. click:run::154deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
line 155why, one step back155 invoke(cli, prog_name='my-app', args=['validate', 'build'])Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
line 156why, one step back156deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
line 157why, one step back157When using chaining, there are a few restrictions:Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
line 158why, one step back158deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
lines 159–165why, one step back159- Only the last command may use ``nargs=-1`` on an argument, otherwise the160 parser will not be able to find further commands.161- It is not possible to nest groups below a chain group.162- On the command line, options must be specified before arguments for each163 command in the chain.164- The :attr:`Context.invoked_subcommand` attribute will be ``'*'`` because the165 parser doesn't know the full list of commands that will run yet.Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
line 166why, one step back166Merge stable into main (#2799)Rowlando13before adoptiond791537
line 167why, one step back167.. _command-pipelines:Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
line 168why, one step back168deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
line 169why, one step back169Command PipelinesMerge stable into main (#2799)Rowlando13before adoptiond791537
line 170why, one step back170------------------Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
line 171why, one step back171deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
lines 172–173why, one step back172When using chaining, a common pattern is to have each command process the173result of the previous command.Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
line 174why, one step back174deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
lines 175–176why, one step back175A straightforward way to do this is to use :func:`make_pass_decorator` to pass176a context object to each command, and store and read the data on that object.Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
lines 177–179why, one step back177178.. click:example::179deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
lines 180–181why, one step back180 pass_ns = click.make_pass_decorator(dict, ensure=True)181Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
line 182why, one step back182 @click.group(chain=True)deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
lines 183–186why, one step back183 @click.argument("name")184 @pass_ns185 def cli(ns, name):186 ns["name"] = nameMerge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
line 187why, one step back187deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
lines 188–191why, one step back188 @cli.command189 @pass_ns190 def lower(ns):191 ns["name"] = ns["name"].lower()Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
line 192why, one step back192deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
lines 193–196why, one step back193 @cli.command194 @pass_ns195 def show(ns):196 click.echo(ns["name"])Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
lines 197–199why, one step back197198.. click:run::199deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
line 200why, one step back200 invoke(cli, prog_name="process", args=["Click", "show", "lower", "show"])Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
line 201why, one step back201deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
lines 202–206why, one step back202Another way to do this is to collect data returned by each command, then process203it at the end of the chain. Use the group's :meth:`~Group.result_callback`204decorator to register a function that is called after the chain is finished. It205is passed the list of return values as well as any parameters registered on the206group.Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
line 207why, one step back207deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
lines 208–212why, one step back208A command can return anything, including a function. Here's an example of that,209where each subcommand creates a function that processes the input, then the210result callback calls each function. The command takes a file, processes each211line, then outputs it. If no subcommands are given, it outputs the contents212of the file unchanged.Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
line 213why, one step back213deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
line 214why, one step back214.. code-block:: pythonMerge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
lines 215–216why, one step back215216 @click.group(chain=True, invoke_without_command=True)deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
lines 217–218why, one step back217 @click.argument("fin", type=click.File("r"))218 def cli(fin):Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
lines 219–221why, one step back219 pass220221 @cli.result_callback()deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
lines 222–224why, one step back222 def process_pipeline(processors, fin):223 iterator = (x.rstrip("\r\n") for x in input)224Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
lines 225–226why, one step back225 for processor in processors:226 iterator = processor(iterator)deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
line 227why, one step back227Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
lines 228–230why, one step back228 for item in iterator:229 click.echo(item)230deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
line 231why, one step back231 @cli.command("upper")Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
lines 232–237why, one step back232 def make_uppercase():233 def processor(iterator):234 for line in iterator:235 yield line.upper()236 return processor237deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
line 238why, one step back238 @cli.command("lower")Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
lines 239–244why, one step back239 def make_lowercase():240 def processor(iterator):241 for line in iterator:242 yield line.lower()243 return processor244deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
line 245why, one step back245 @cli.command("strip")Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
lines 246–279why, one step back246 def make_strip():247 def processor(iterator):248 for line in iterator:249 yield line.strip()250 return processor251252That's a lot in one go, so let's go through it step by step.2532541. The first thing is to make a :func:`group` that is chainable. In255 addition to that we also instruct Click to invoke even if no256 subcommand is defined. If this would not be done, then invoking an257 empty pipeline would produce the help page instead of running the258 result callbacks.2592. The next thing we do is to register a result callback on our group.260 This callback will be invoked with an argument which is the list of261 all return values of all subcommands and then the same keyword262 parameters as our group itself. This means we can access the input263 file easily there without having to use the context object.2643. In this result callback we create an iterator of all the lines in the265 input file and then pass this iterator through all the returned266 callbacks from all subcommands and finally we print all lines to267 stdout.268269After that point we can register as many subcommands as we want and each270subcommand can return a processor function to modify the stream of lines.271272One important thing of note is that Click shuts down the context after273each callback has been run. This means that for instance file types274cannot be accessed in the `processor` functions as the files will already275be closed there. This limitation is unlikely to change because it would276make resource handling much more complicated. For such it's recommended277to not use the file type and manually open the file through278:func:`open_file`.279deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
lines 280–282why, one step back280For a more complex example that also improves upon handling of the pipelines,281see the `imagepipe example`_ in the Click repository. It implements a282pipeline based image editing tool that has a nice internal structure.Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
line 283why, one step back283deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
line 284why, one step back284.. _imagepipe example: https://github.com/pallets/click/tree/main/examples/imagepipeMerge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
line 285why, one step back285deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
line 286why, one step back286Merge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
lines 287–394why, one step back287Overriding Defaults288-------------------289290By default, the default value for a parameter is pulled from the291``default`` flag that is provided when it's defined, but that's not the292only place defaults can be loaded from. The other place is the293:attr:`Context.default_map` (a dictionary) on the context. This allows294defaults to be loaded from a configuration file to override the regular295defaults.296297This is useful if you plug in some commands from another package but298you're not satisfied with the defaults.299300The default map can be nested arbitrarily for each subcommand:301302.. code-block:: python303304 default_map = {305 "debug": True, # default for a top level option306 "runserver": {"port": 5000} # default for a subcommand307 }308309The default map can be provided when the script is invoked, or310overridden at any point by commands. For instance, a top-level command311could load the defaults from a configuration file.312313Example usage:314315.. click:example::316317 import click318319 @click.group()320 def cli():321 pass322323 @cli.command()324 @click.option('--port', default=8000)325 def runserver(port):326 click.echo(f"Serving on http://127.0.0.1:{port}/")327328 if __name__ == '__main__':329 cli(default_map={330 'runserver': {331 'port': 5000332 }333 })334335And in action:336337.. click:run::338339 invoke(cli, prog_name='cli', args=['runserver'], default_map={340 'runserver': {341 'port': 5000342 }343 })344345Context Defaults346----------------347348.. versionadded:: 2.0349350Starting with Click 2.0 you can override defaults for contexts not just351when calling your script, but also in the decorator that declares a352command. For instance given the previous example which defines a custom353``default_map`` this can also be accomplished in the decorator now.354355This example does the same as the previous example:356357.. click:example::358359 import click360361 CONTEXT_SETTINGS = dict(362 default_map={'runserver': {'port': 5000}}363 )364365 @click.group(context_settings=CONTEXT_SETTINGS)366 def cli():367 pass368369 @cli.command()370 @click.option('--port', default=8000)371 def runserver(port):372 click.echo(f"Serving on http://127.0.0.1:{port}/")373374 if __name__ == '__main__':375 cli()376377And again the example in action:378379.. click:run::380381 invoke(cli, prog_name='cli', args=['runserver'])382383384Command Return Values385---------------------386387.. versionadded:: 3.0388389One of the new introductions in Click 3.0 is the full support for return390values from command callbacks. This enables a whole range of features391that were previously hard to implement.392393In essence any command callback can now return a value. This return value394is bubbled to certain receivers. One usecase for this has already beendeprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
lines 395–396why, one step back395show in the example of :ref:`command-chaining` where it has been396demonstrated that chained groups can have callbacks that processMerge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
lines 397–402why, one step back397all return values.398399When working with command return values in Click, this is what you need to400know:401402- The return value of a command callback is generally returned from thedeprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
line 403why, one step back403 :meth:`Command.invoke` method. The exception to this rule has toMerge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
lines 404–412why, one step back404 do with :class:`Group`\s:405406 * In a group the return value is generally the return value of the407 subcommand invoked. The only exception to this rule is that the408 return value is the return value of the group callback if it's409 invoked without arguments and `invoke_without_command` is enabled.410 * If a group is set up for chaining then the return value is a list411 of all subcommands' results.412 * Return values of groups can be processed through adeprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
line 413why, one step back413 :attr:`Group.result_callback`. This is invoked with theMerge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
lines 414–422why, one step back414 list of all return values in chain mode, or the single return415 value in case of non chained commands.416417- The return value is bubbled through from the :meth:`Context.invoke`418 and :meth:`Context.forward` methods. This is useful in situations419 where you internally want to call into another command.420421- Click does not have any hard requirements for the return values and422 does not use them itself. This allows return values to be used fordeprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
line 423why, one step back423 custom decorators or workflows (like in the command chainingMerge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
lines 424–426why, one step back424 example).425426- When a Click script is invoked as command line application (throughdeprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
line 427why, one step back427 :meth:`Command.main`) the return value is ignored unless theMerge pull request #2266 from pallets/dependabot/github_actions/actions/cache-3.0.2David Lordbefore adoptionc96545f
line 428why, one step back428 `standalone_mode` is disabled in which case it's bubbled through.