Skip to content
Myr

commands.rst

This file

Path

docs/commands.rst

558 lines · 18.0 KiB

Last changed by

Fix typos in docs (#623)Radovan Bastbefore adoptionb5239af

History of this file

Take it

The walk stopped after 200 commits: lines older than e413626 point at it.

Added some docs on return values from commandsArmin Ronacherbefore adoptione413626

lines 1–137why, one step back
1Commands and Groups
2===================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('Debug mode is %s' % ('on' if debug else 'off'))2930 @cli.command()31 def sync():32 click.echo('Synching')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 ctx.obj['DEBUG'] = debug9192 @cli.command()93 @click.pass_context94 def sync(ctx):95 click.echo('Debug is %s' % (ctx.obj['DEBUG'] and 'on' or 'off'))9697 if __name__ == '__main__':98 cli(obj={})99100If the object is provided, each context will pass the object onwards to101its children, but at any level a context's object can be overridden. To102reach to a parent, ``context.parent`` can be used.103104In addition to that, instead of passing an object down, nothing stops the105application from modifying global state. For instance, you could just flip106a global ``DEBUG`` variable and be done with it.107108Decorating Commands109-------------------110111As you have seen in the earlier example, a decorator can change how a112command is invoked. What actually happens behind the scenes is that113callbacks are always invoked through the :meth:`Context.invoke` method114which automatically invokes a command correctly (by either passing the115context or not).116117This is very useful when you want to write custom decorators. For118instance, a common pattern would be to configure an object representing119state and then storing it on the context and then to use a custom120decorator to find the most recent object of this sort and pass it as first121argument.122123For instance, the :func:`pass_obj` decorator can be implemented like this:124125.. click:example::126127 from functools import update_wrapper128129 def pass_obj(f):130 @click.pass_context131 def new_func(ctx, *args, **kwargs):132 return ctx.invoke(f, ctx.obj, *args, **kwargs)133 return update_wrapper(new_func, f)134135The :meth:`Context.invoke` command will automatically invoke the function136in the correct way, so the function will either be called with ``f(ctx,137obj)`` or ``f(obj)`` depending on whether or not it itself is decorated with

Merge pull request #291 from jhermann/patch-2Markus Unterwaditzerbefore adoption6a03b34

line 138why, one step back
138:func:`pass_context`.

Added some docs on return values from commandsArmin Ronacherbefore adoptione413626

line 139why, one step back
139

Merge pull request #290 from jhermann/patch-1Markus Unterwaditzerbefore adoption2fa23f0

line 140why, one step back
140This is a very powerful concept that can be used to build very complex

Added some docs on return values from commandsArmin Ronacherbefore adoptione413626

lines 141–170why, one step back
141nested applications; see :ref:`complex-guide` for more information.
142143144Group Invocation Without Command145--------------------------------146147By default, a group or multi command is not invoked unless a subcommand is148passed. In fact, not providing a command automatically passes ``--help``149by default. This behavior can be changed by passing150``invoke_without_command=True`` to a group. In that case, the callback is151always invoked instead of showing the help page. The context object also152includes information about whether or not the invocation would go to a153subcommand.154155Example:156157.. click:example::158159 @click.group(invoke_without_command=True)160 @click.pass_context161 def cli(ctx):162 if ctx.invoked_subcommand is None:163 click.echo('I was invoked without subcommand')164 else:165 click.echo('I am about to invoke %s' % ctx.invoked_subcommand)166167 @cli.command()168 def sync():169 click.echo('The subcommand')170

Merge branch '3.x-maintenance'Armin Ronacherbefore adoption733d5fa

line 171why, one step back
171And how it works in practice:

Added some docs on return values from commandsArmin Ronacherbefore adoptione413626

line 172why, one step back
172

Merge branch '3.x-maintenance'Armin Ronacherbefore adoption733d5fa

line 173why, one step back
173.. click:run::

Added some docs on return values from commandsArmin Ronacherbefore adoptione413626

line 174why, one step back
174

Merge branch '3.x-maintenance'Armin Ronacherbefore adoption733d5fa

lines 175–177why, one step back
175 invoke(cli, prog_name='tool', args=[])
176 invoke(cli, prog_name='tool', args=['sync'])177

Added some docs on return values from commandsArmin Ronacherbefore adoptione413626

lines 178–284why, one step back
178.. _custom-multi-commands:
179180Custom Multi Commands181---------------------182183In addition to using :func:`click.group`, you can also build your own184custom multi commands. This is useful when you want to support commands185being loaded lazily from plugins.186187A custom multi command just needs to implement a list and load method:188189.. click:example::190191 import click192 import os193194 plugin_folder = os.path.join(os.path.dirname(__file__), 'commands')195196 class MyCLI(click.MultiCommand):197198 def list_commands(self, ctx):199 rv = []200 for filename in os.listdir(plugin_folder):201 if filename.endswith('.py'):202 rv.append(filename[:-3])203 rv.sort()204 return rv205206 def get_command(self, ctx, name):207 ns = {}208 fn = os.path.join(plugin_folder, name + '.py')209 with open(fn) as f:210 code = compile(f.read(), fn, 'exec')211 eval(code, ns, ns)212 return ns['cli']213214 cli = MyCLI(help='This tool\'s subcommands are loaded from a '215 'plugin folder dynamically.')216217 if __name__ == '__main__':218 cli()219220These custom classes can also be used with decorators:221222.. click:example::223224 @click.command(cls=MyCLI)225 def cli():226 pass227228Merging Multi Commands229----------------------230231In addition to implementing custom multi commands, it can also be232interesting to merge multiple together into one script. While this is233generally not as recommended as it nests one below the other, the merging234approach can be useful in some circumstances for a nicer shell experience.235236The default implementation for such a merging system is the237:class:`CommandCollection` class. It accepts a list of other multi238commands and makes the commands available on the same level.239240Example usage:241242.. click:example::243244 import click245246 @click.group()247 def cli1():248 pass249250 @cli1.command()251 def cmd1():252 """Command on cli1"""253254 @click.group()255 def cli2():256 pass257258 @cli2.command()259 def cmd2():260 """Command on cli2"""261262 cli = click.CommandCollection(sources=[cli1, cli2])263264 if __name__ == '__main__':265 cli()266267And what it looks like:268269.. click:run::270271 invoke(cli, prog_name='cli', args=['--help'])272273In case a command exists in more than one source, the first source wins.274275276.. _multi-command-chaining:277278Multi Command Chaining279----------------------280281.. versionadded:: 3.0282283Sometimes it is useful to be allowed to invoke more than one subcommand in284one go. For instance if you have installed a setuptools package before

Merge pull request #306 from bionikspoon/patch-2Markus Unterwaditzerbefore adoptiona25d551

line 285why, one step back
285you might be familiar with the ``setup.py sdist bdist_wheel upload``

Added some docs on return values from commandsArmin Ronacherbefore adoptione413626

lines 286–312why, one step back
286command chain which invokes ``dist`` before ``bdist_wheel`` before
287``upload``. Starting with Click 3.0 this is very simple to implement.288All you have to do is to pass ``chain=True`` to your multicommand:289290.. click:example::291292 @click.group(chain=True)293 def cli():294 pass295296297 @cli.command('sdist')298 def sdist():299 click.echo('sdist called')300301302 @cli.command('bdist_wheel')303 def bdist_wheel():304 click.echo('bdist_wheel called')305306Now you can invoke it like this:307308.. click:run::309310 invoke(cli, prog_name='setup.py', args=['sdist', 'bdist_wheel'])311312When using multi command chaining you can only have one command (the last)

We're not rejecting multi commands below chained multi commands. This fixes #415Armin Ronacherbefore adoption5620b05

lines 313–314why, one step back
313use ``nargs=-1`` on an argument. It is also not possible to nest multi
314commands below chained multicommands. Other than that there are no

Added some docs on return values from commandsArmin Ronacherbefore adoptione413626

lines 315–319why, one step back
315restrictions on how they work. They can accept options and arguments as
316normal.317318Another note: the :attr:`Context.invoked_subcommand` attribute is a bit319useless for multi commands as it will give ``'*'`` as value if more than

Merge branch '3.x-maintenance'Armin Ronacherbefore adoption733d5fa

lines 320–322why, one step back
320one command is invoked. This is necessary because the handling of
321subcommands happens one after another so the exact subcommands that will322be handled are not yet available when the callback fires.

Added some docs on return values from commandsArmin Ronacherbefore adoptione413626

line 323why, one step back
323

Merge branch '6.x-maintenance'Armin Ronacherbefore adoption6fcda3e

line 324why, one step back
324.. note::

Added some docs on return values from commandsArmin Ronacherbefore adoptione413626

line 325why, one step back
325

Merge branch '6.x-maintenance'Armin Ronacherbefore adoption6fcda3e

lines 326–327why, one step back
326 It is currently not possible for chain commands to be nested. This
327 will be fixed in future versions of Click.

Implemented nesting below chain commands.Armin Ronacherbefore adoption0a2919f

lines 328–329why, one step back
328
329

Added some docs on return values from commandsArmin Ronacherbefore adoptione413626

lines 330–339why, one step back
330Multi Command Pipelines
331-----------------------332333.. versionadded:: 3.0334335A very common usecase of multi command chaining is to have one command336process the result of the previous command. There are various ways in337which this can be facilitated. The most obvious way is to store a value338on the context object and process it from function to function. This339works by decorating a function with :func:`pass_context` after which the

Merge pull request #385 from gordonfierce/TyposMarkus Unterwaditzerbefore adoption2324202

line 340why, one step back
340context object is provided and a subcommand can store its data there.

Added some docs on return values from commandsArmin Ronacherbefore adoptione413626

lines 341–343why, one step back
341
342Another way to accomplish this is to setup pipelines by returning343processing functions. Think of it like this: when a subcommand gets

Merge pull request #385 from gordonfierce/TyposMarkus Unterwaditzerbefore adoption2324202

lines 344–345why, one step back
344invoked it processes all of its parameters and comes up with a plan of
345how to do its processing. At that point it then returns a processing

Added some docs on return values from commandsArmin Ronacherbefore adoptione413626

lines 346–419why, one step back
346function and returns.
347348Where do the returned functions go? The chained multicommand can register349a callback with :meth:`MultiCommand.resultcallback` that goes over all350these functions and then invoke them.351352To make this a bit more concrete consider this example:353354.. click:example::355356 @click.group(chain=True, invoke_without_command=True)357 @click.option('-i', '--input', type=click.File('r'))358 def cli(input):359 pass360361 @cli.resultcallback()362 def process_pipeline(processors, input):363 iterator = (x.rstrip('\r\n') for x in input)364 for processor in processors:365 iterator = processor(iterator)366 for item in iterator:367 click.echo(item)368369 @cli.command('uppercase')370 def make_uppercase():371 def processor(iterator):372 for line in iterator:373 yield line.upper()374 return processor375376 @cli.command('lowercase')377 def make_lowercase():378 def processor(iterator):379 for line in iterator:380 yield line.lower()381 return processor382383 @cli.command('strip')384 def make_strip():385 def processor(iterator):386 for line in iterator:387 yield line.strip()388 return processor389390That's a lot in one go, so let's go through it step by step.3913921. The first thing is to make a :func:`group` that is chainable. In393 addition to that we also instruct Click to invoke even if no394 subcommand is defined. If this would not be done, then invoking an395 empty pipeline would produce the help page instead of running the396 result callbacks.3972. The next thing we do is to register a result callback on our group.398 This callback will be invoked with an argument which is the list of399 all return values of all subcommands and then the same keyword400 parameters as our group itself. This means we can access the input401 file easily there without having to use the context object.4023. In this result callback we create an iterator of all the lines in the403 input file and then pass this iterator through all the returned404 callbacks from all subcommands and finally we print all lines to405 stdout.406407After that point we can register as many subcommands as we want and each408subcommand can return a processor function to modify the stream of lines.409410One important thing of note is that Click shuts down the context after411each callback has been run. This means that for instance file types412cannot be accessed in the `processor` functions as the files will already413be closed there. This limitation is unlikely to change because it would414make resource handling much more complicated. For such it's recommended415to not use the file type and manually open the file through416:func:`open_file`.417418For a more complex example that also improves upon handling of the419pipelines have a look at the `imagepipe multi command chaining demo

Merge pull request #550 from quobit/pallets-reallocationMarkus Unterwaditzerbefore adoption2489a7e

line 420why, one step back
420<https://github.com/pallets/click/tree/master/examples/imagepipe>`__ in

Added some docs on return values from commandsArmin Ronacherbefore adoptione413626

lines 421–439why, one step back
421the Click repository. It implements a pipeline based image editing tool
422that has a nice internal structure for the pipelines.423424425Overriding Defaults426-------------------427428By default, the default value for a parameter is pulled from the429``default`` flag that is provided when it's defined, but that's not the430only place defaults can be loaded from. The other place is the431:attr:`Context.default_map` (a dictionary) on the context. This allows432defaults to be loaded from a configuration file to override the regular433defaults.434435This is useful if you plug in some commands from another package but436you're not satisfied with the defaults.437438The default map can be nested arbitrarily for each subcommand and439provided when the script is invoked. Alternatively, it can also be

Fix typos in docs (#623)Radovan Bastbefore adoptionb5239af

line 440why, one step back
440overridden at any point by commands. For instance, a top-level command could

Added some docs on return values from commandsArmin Ronacherbefore adoptione413626

lines 441–558why, one step back
441load the defaults from a configuration file.
442443Example usage:444445.. click:example::446447 import click448449 @click.group()450 def cli():451 pass452453 @cli.command()454 @click.option('--port', default=8000)455 def runserver(port):456 click.echo('Serving on http://127.0.0.1:%d/' % port)457458 if __name__ == '__main__':459 cli(default_map={460 'runserver': {461 'port': 5000462 }463 })464465And in action:466467.. click:run::468469 invoke(cli, prog_name='cli', args=['runserver'], default_map={470 'runserver': {471 'port': 5000472 }473 })474475Context Defaults476----------------477478.. versionadded:: 2.0479480Starting with Click 2.0 you can override defaults for contexts not just481when calling your script, but also in the decorator that declares a482command. For instance given the previous example which defines a custom483``default_map`` this can also be accomplished in the decorator now.484485This example does the same as the previous example:486487.. click:example::488489 import click490491 CONTEXT_SETTINGS = dict(492 default_map={'runserver': {'port': 5000}}493 )494495 @click.group(context_settings=CONTEXT_SETTINGS)496 def cli():497 pass498499 @cli.command()500 @click.option('--port', default=8000)501 def runserver(port):502 click.echo('Serving on http://127.0.0.1:%d/' % port)503504 if __name__ == '__main__':505 cli()506507And again the example in action:508509.. click:run::510511 invoke(cli, prog_name='cli', args=['runserver'])512513514Command Return Values515---------------------516517.. versionadded:: 3.0518519One of the new introductions in Click 3.0 is the full support for return520values from command callbacks. This enables a whole range of features521that were previously hard to implement.522523In essence any command callback can now return a value. This return value524is bubbled to certain receivers. One usecase for this has already been525show in the example of :ref:`multi-command-chaining` where it has been526demonstrated that chained multi commands can have callbacks that process527all return values.528529When working with command return values in Click, this is what you need to530know:531532- The return value of a command callback is generally returned from the533 :meth:`BaseCommand.invoke` method. The exception to this rule has to534 do with :class:`Group`\s:535536 * In a group the return value is generally the return value of the537 subcommand invoked. The only exception to this rule is that the538 return value is the return value of the group callback if it's539 invoked without arguments and `invoke_without_command` is enabled.540 * If a group is set up for chaining then the return value is a list541 of all subcommands' results.542 * Return values of groups can be processed through a543 :attr:`MultiCommand.result_callback`. This is invoked with the544 list of all return values in chain mode, or the single return545 value in case of non chained commands.546547- The return value is bubbled through from the :meth:`Context.invoke`548 and :meth:`Context.forward` methods. This is useful in situations549 where you internally want to call into another command.550551- Click does not have any hard requirements for the return values and552 does not use them itself. This allows return values to be used for553 custom decorators or workflows (like in the multi command chaining554 example).555556- When a Click script is invoked as command line application (through557 :meth:`BaseCommand.main`) the return value is ignored unless the558 `standalone_mode` is disabled in which case it's bubbled through.