commands.rst
This file
Path
docs/commands.rst
552 lines · 17.8 KiB
Last changed by
Merge pull request #385 from gordonfierce/TyposMarkus Unterwaditzerbefore adoption2324202
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('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 with138:func:`pass_context`.139140This is a very powerful concept that can be used to build very complex141nested 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')170171And how it works in practice:172173.. click:run::174175 invoke(cli, prog_name='tool', args=[])176 invoke(cli, prog_name='tool', args=['sync'])177178.. _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 before285you might be familiar with the ``setup.py sdist bdist_wheel upload``286command chain which invokes ``dist`` before ``bdist_wheel`` before287``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)313use ``nargs=-1`` on an argument. Other than that there are no314restrictions on how they work. They can accept options and arguments as315normal.316317Another note: the :attr:`Context.invoked_subcommand` attribute is a bit318useless for multi commands as it will give ``'*'`` as value if more than319one command is invoked. This is necessary because the handling of320subcommands happens one after another so the exact subcommands that will321be handled are not yet available when the callback fires.322323324Multi Command Pipelines325-----------------------326327.. versionadded:: 3.0328329A very common usecase of multi command chaining is to have one command330process the result of the previous command. There are various ways in331which this can be facilitated. The most obvious way is to store a value332on the context object and process it from function to function. This333works by decorating a function with :func:`pass_context` after which the334context object is provided and a subcommand can store its data there.335336Another way to accomplish this is to setup pipelines by returning337processing functions. Think of it like this: when a subcommand gets338invoked it processes all of its parameters and comes up with a plan of339how to do its processing. At that point it then returns a processing340function and returns.341342Where do the returned functions go? The chained multicommand can register343a callback with :meth:`MultiCommand.resultcallback` that goes over all344these functions and then invoke them.345346To make this a bit more concrete consider this example:347348.. click:example::349350 @click.group(chain=True, invoke_without_command=True)351 @click.option('-i', '--input', type=click.File('r'))352 def cli(input):353 pass354355 @cli.resultcallback()356 def process_pipeline(processors, input):357 iterator = (x.rstrip('\r\n') for x in input)358 for processor in processors:359 iterator = processor(iterator)360 for item in iterator:361 click.echo(item)362363 @cli.command('uppercase')364 def make_uppercase():365 def processor(iterator):366 for line in iterator:367 yield line.upper()368 return processor369370 @cli.command('lowercase')371 def make_lowercase():372 def processor(iterator):373 for line in iterator:374 yield line.lower()375 return processor376377 @cli.command('strip')378 def make_strip():379 def processor(iterator):380 for line in iterator:381 yield line.strip()382 return processor383384That's a lot in one go, so let's go through it step by step.3853861. The first thing is to make a :func:`group` that is chainable. In387 addition to that we also instruct Click to invoke even if no388 subcommand is defined. If this would not be done, then invoking an389 empty pipeline would produce the help page instead of running the390 result callbacks.3912. The next thing we do is to register a result callback on our group.392 This callback will be invoked with an argument which is the list of393 all return values of all subcommands and then the same keyword394 parameters as our group itself. This means we can access the input395 file easily there without having to use the context object.3963. In this result callback we create an iterator of all the lines in the397 input file and then pass this iterator through all the returned398 callbacks from all subcommands and finally we print all lines to399 stdout.400401After that point we can register as many subcommands as we want and each402subcommand can return a processor function to modify the stream of lines.403404One important thing of note is that Click shuts down the context after405each callback has been run. This means that for instance file types406cannot be accessed in the `processor` functions as the files will already407be closed there. This limitation is unlikely to change because it would408make resource handling much more complicated. For such it's recommended409to not use the file type and manually open the file through410:func:`open_file`.411412For a more complex example that also improves upon handling of the413pipelines have a look at the `imagepipe multi command chaining demo414<https://github.com/mitsuhiko/click/tree/master/examples/imagepipe>`__ in415the Click repository. It implements a pipeline based image editing tool416that has a nice internal structure for the pipelines.417418419Overriding Defaults420-------------------421422By default, the default value for a parameter is pulled from the423``default`` flag that is provided when it's defined, but that's not the424only place defaults can be loaded from. The other place is the425:attr:`Context.default_map` (a dictionary) on the context. This allows426defaults to be loaded from a configuration file to override the regular427defaults.428429This is useful if you plug in some commands from another package but430you're not satisfied with the defaults.431432The default map can be nested arbitrarily for each subcommand and433provided when the script is invoked. Alternatively, it can also be434overriden at any point by commands. For instance, a top-level command could435load the defaults from a configuration file.436437Example usage:438439.. click:example::440441 import click442443 @click.group()444 def cli():445 pass446447 @cli.command()448 @click.option('--port', default=8000)449 def runserver(port):450 click.echo('Serving on http://127.0.0.1:%d/' % port)451452 if __name__ == '__main__':453 cli(default_map={454 'runserver': {455 'port': 5000456 }457 })458459And in action:460461.. click:run::462463 invoke(cli, prog_name='cli', args=['runserver'], default_map={464 'runserver': {465 'port': 5000466 }467 })468469Context Defaults470----------------471472.. versionadded:: 2.0473474Starting with Click 2.0 you can override defaults for contexts not just475when calling your script, but also in the decorator that declares a476command. For instance given the previous example which defines a custom477``default_map`` this can also be accomplished in the decorator now.478479This example does the same as the previous example:480481.. click:example::482483 import click484485 CONTEXT_SETTINGS = dict(486 default_map={'runserver': {'port': 5000}}487 )488489 @click.group(context_settings=CONTEXT_SETTINGS)490 def cli():491 pass492493 @cli.command()494 @click.option('--port', default=8000)495 def runserver(port):496 click.echo('Serving on http://127.0.0.1:%d/' % port)497498 if __name__ == '__main__':499 cli()500501And again the example in action:502503.. click:run::504505 invoke(cli, prog_name='cli', args=['runserver'])506507508Command Return Values509---------------------510511.. versionadded:: 3.0512513One of the new introductions in Click 3.0 is the full support for return514values from command callbacks. This enables a whole range of features515that were previously hard to implement.516517In essence any command callback can now return a value. This return value518is bubbled to certain receivers. One usecase for this has already been519show in the example of :ref:`multi-command-chaining` where it has been520demonstrated that chained multi commands can have callbacks that process521all return values.522523When working with command return values in Click, this is what you need to524know:525526- The return value of a command callback is generally returned from the527 :meth:`BaseCommand.invoke` method. The exception to this rule has to528 do with :class:`Group`\s:529530 * In a group the return value is generally the return value of the531 subcommand invoked. The only exception to this rule is that the532 return value is the return value of the group callback if it's533 invoked without arguments and `invoke_without_command` is enabled.534 * If a group is set up for chaining then the return value is a list535 of all subcommands' results.536 * Return values of groups can be processed through a537 :attr:`MultiCommand.result_callback`. This is invoked with the538 list of all return values in chain mode, or the single return539 value in case of non chained commands.540541- The return value is bubbled through from the :meth:`Context.invoke`542 and :meth:`Context.forward` methods. This is useful in situations543 where you internally want to call into another command.544545- Click does not have any hard requirements for the return values and546 does not use them itself. This allows return values to be used for547 custom decorators or workflows (like in the multi command chaining548 example).549550- When a Click script is invoked as command line application (through551 :meth:`BaseCommand.main`) the return value is ignored unless the552 `standalone_mode` is disabled in which case it's bubbled through.