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
The walk stopped after 200 commits: lines older than 502c86b point at it.
open -> launchArmin Ronacherbefore adoption502c86b
lines 1–5why, one step back1Commands and Groups2===================34.. currentmodule:: click5Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 6why, one step back6The most important feature of Click is the concept of arbitrarily nestingopen -> launchArmin Ronacherbefore adoption502c86b
lines 7–12why, one step back7command line utilities. This is implemented through the :class:`Command`8and :class:`Group` (actually :class:`MultiCommand`).910Callback Invocation11-------------------12Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 13why, one step back13For a regular command, the callback is executed whenever the command runs.Merge pull request #163 from untitaker/doc_fixesArmin Ronacherbefore adoption19c8458
lines 14–16why, one step back14If 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).open -> launchArmin Ronacherbefore adoption502c86b
line 17why, one step back17Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 18why, one step back18For groups and multi commands, the situation looks different. In this case,open -> launchArmin Ronacherbefore adoption502c86b
lines 19–40why, one step back19the 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'])Merge pull request #163 from untitaker/doc_fixesArmin Ronacherbefore adoption19c8458
lines 41–60why, one step back4142Passing 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.open -> launchArmin Ronacherbefore adoption502c86b
lines 61–64why, one step back6162Nested Handling and Contexts63----------------------------64Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 65why, one step back65As you can see from the earlier example, the basic command group accepts aopen -> launchArmin Ronacherbefore adoption502c86b
lines 66–68why, one step back66debug argument which is passed to its callback, but not to the sync67command itself. The sync command only accepts its own arguments.68Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 69why, one step back69This allows tools to act completely independent of each other, but howopen -> launchArmin Ronacherbefore adoption502c86b
lines 70–72why, one step back70does one command talk to a nested one? The answer to this is the71:class:`Context`.72Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 73–74why, one step back73Each time a command is invoked, a new context is created and linked with the74parent context. Normally, you can't see these contexts, but they areopen -> launchArmin Ronacherbefore adoption502c86b
lines 75–77why, one step back75there. 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 thatMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 78why, one step back78case, the context is passed as first argument.open -> launchArmin Ronacherbefore adoption502c86b
lines 79–99why, one step back7980The 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={})99Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 100why, one step back100If the object is provided, each context will pass the object onwards toopen -> launchArmin Ronacherbefore adoption502c86b
line 101why, one step back101its children, but at any level a context's object can be overridden. ToMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 102why, one step back102reach to a parent, ``context.parent`` can be used.open -> launchArmin Ronacherbefore adoption502c86b
line 103why, one step back103Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 104–105why, one step back104In addition to that, instead of passing an object down, nothing stops the105application from modifying global state. For instance, you could just flipopen -> launchArmin Ronacherbefore adoption502c86b
lines 106–110why, one step back106a global ``DEBUG`` variable and be done with it.107108Decorating Commands109-------------------110Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 111why, one step back111As you have seen in the earlier example, a decorator can change how aopen -> launchArmin Ronacherbefore adoption502c86b
lines 112–117why, one step back112command 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. ForMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 118why, one step back118instance, a common pattern would be to configure an object representingopen -> launchArmin Ronacherbefore adoption502c86b
lines 119–122why, one step back119state 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.122Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 123why, one step back123For instance, the :func:`pass_obj` decorator can be implemented like this:open -> launchArmin Ronacherbefore adoption502c86b
lines 124–135why, one step back124125.. 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 functionMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 136why, one step back136in the correct way, so the function will either be called with ``f(ctx,Documentation fixesKevin Yapbefore adoption67523af
line 137why, one step back137obj)`` or ``f(obj)`` depending on whether or not it itself is decorated withMerge pull request #291 from jhermann/patch-2Markus Unterwaditzerbefore adoption6a03b34
line 138why, one step back138:func:`pass_context`.open -> launchArmin Ronacherbefore adoption502c86b
line 139why, one step back139Merge pull request #290 from jhermann/patch-1Markus Unterwaditzerbefore adoption2fa23f0
line 140why, one step back140This is a very powerful concept that can be used to build very complexDocumentation fixesKevin Yapbefore adoption67523af
line 141why, one step back141nested applications; see :ref:`complex-guide` for more information.open -> launchArmin Ronacherbefore adoption502c86b
lines 142–146why, one step back142143144Group Invocation Without Command145--------------------------------146Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 147why, one step back147By default, a group or multi command is not invoked unless a subcommand isopen -> launchArmin Ronacherbefore adoption502c86b
lines 148–149why, one step back148passed. In fact, not providing a command automatically passes ``--help``149by default. This behavior can be changed by passingMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 150why, one step back150``invoke_without_command=True`` to a group. In that case, the callback isopen -> launchArmin Ronacherbefore adoption502c86b
line 151why, one step back151always invoked instead of showing the help page. The context object alsoMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 152–153why, one step back152includes information about whether or not the invocation would go to a153subcommand.open -> launchArmin Ronacherbefore adoption502c86b
lines 154–170why, one step back154155Example: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')170Merge branch '3.x-maintenance'Armin Ronacherbefore adoption733d5fa
line 171why, one step back171And how it works in practice:open -> launchArmin Ronacherbefore adoption502c86b
line 172why, one step back172Merge branch '3.x-maintenance'Armin Ronacherbefore adoption733d5fa
line 173why, one step back173.. click:run::open -> launchArmin Ronacherbefore adoption502c86b
line 174why, one step back174Merge branch '3.x-maintenance'Armin Ronacherbefore adoption733d5fa
lines 175–177why, one step back175 invoke(cli, prog_name='tool', args=[])176 invoke(cli, prog_name='tool', args=['sync'])177open -> launchArmin Ronacherbefore adoption502c86b
lines 178–182why, one step back178.. _custom-multi-commands:179180Custom Multi Commands181---------------------182Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 183why, one step back183In addition to using :func:`click.group`, you can also build your ownopen -> launchArmin Ronacherbefore adoption502c86b
lines 184–230why, one step back184custom 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----------------------230Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 231why, one step back231In addition to implementing custom multi commands, it can also beopen -> launchArmin Ronacherbefore adoption502c86b
line 232why, one step back232interesting to merge multiple together into one script. While this isDocumentation fixesKevin Yapbefore adoption67523af
line 233why, one step back233generally not as recommended as it nests one below the other, the mergingopen -> launchArmin Ronacherbefore adoption502c86b
lines 234–235why, one step back234approach can be useful in some circumstances for a nicer shell experience.235Documentation fixesKevin Yapbefore adoption67523af
line 236why, one step back236The default implementation for such a merging system is theopen -> launchArmin Ronacherbefore adoption502c86b
line 237why, one step back237:class:`CommandCollection` class. It accepts a list of other multiMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 238why, one step back238commands and makes the commands available on the same level.open -> launchArmin Ronacherbefore adoption502c86b
lines 239–272why, one step back239240Example 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'])272Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 273why, one step back273In case a command exists in more than one source, the first source wins.open -> launchArmin Ronacherbefore adoption502c86b
line 274why, one step back274Added pipeline documentation exampleArmin Ronacherbefore adoptionc0b076e
line 275why, one step back275Added some docs on return values from commandsArmin Ronacherbefore adoptione413626
lines 276–277why, one step back276.. _multi-command-chaining:277Added subcommand chaining.Armin Ronacherbefore adoption8d0dfa5
lines 278–284why, one step back278Multi 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 beforeMerge pull request #306 from bionikspoon/patch-2Markus Unterwaditzerbefore adoptiona25d551
line 285why, one step back285you might be familiar with the ``setup.py sdist bdist_wheel upload``Added subcommand chaining.Armin Ronacherbefore adoption8d0dfa5
lines 286–318why, one step back286command 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 thanMerge branch '3.x-maintenance'Armin Ronacherbefore adoption733d5fa
lines 319–321why, one step back319one 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.Added pipeline documentation exampleArmin Ronacherbefore adoptionc0b076e
lines 322–333why, one step back322323324Multi 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 theMerge pull request #385 from gordonfierce/TyposMarkus Unterwaditzerbefore adoption2324202
line 334why, one step back334context object is provided and a subcommand can store its data there.Added pipeline documentation exampleArmin Ronacherbefore adoptionc0b076e
lines 335–337why, one step back335336Another way to accomplish this is to setup pipelines by returning337processing functions. Think of it like this: when a subcommand getsMerge pull request #385 from gordonfierce/TyposMarkus Unterwaditzerbefore adoption2324202
lines 338–339why, one step back338invoked it processes all of its parameters and comes up with a plan of339how to do its processing. At that point it then returns a processingAdded pipeline documentation exampleArmin Ronacherbefore adoptionc0b076e
lines 340–416why, one step back340function 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.Added subcommand chaining.Armin Ronacherbefore adoption8d0dfa5
lines 417–418why, one step back417418open -> launchArmin Ronacherbefore adoption502c86b
lines 419–421why, one step back419Overriding Defaults420-------------------421Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 422–423why, one step back422By default, the default value for a parameter is pulled from the423``default`` flag that is provided when it's defined, but that's not theopen -> launchArmin Ronacherbefore adoption502c86b
lines 424–425why, one step back424only place defaults can be loaded from. The other place is the425:attr:`Context.default_map` (a dictionary) on the context. This allowsMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
lines 426–427why, one step back426defaults to be loaded from a configuration file to override the regular427defaults.open -> launchArmin Ronacherbefore adoption502c86b
lines 428–431why, one step back428429This is useful if you plug in some commands from another package but430you're not satisfied with the defaults.431Documentation fixesKevin Yapbefore adoption67523af
line 432why, one step back432The default map can be nested arbitrarily for each subcommand andMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 433why, one step back433provided when the script is invoked. Alternatively, it can also beDocumentation fixesKevin Yapbefore adoption67523af
line 434why, one step back434overriden at any point by commands. For instance, a top-level command couldMerge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69
line 435why, one step back435load the defaults from a configuration file.open -> launchArmin Ronacherbefore adoption502c86b
lines 436–458why, one step back436437Example 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 })458Cleaned up context defaults and documented them.Armin Ronacherbefore adoption7d776de
lines 459–460why, one step back459And in action:460open -> launchArmin Ronacherbefore adoption502c86b
lines 461–467why, one step back461.. click:run::462463 invoke(cli, prog_name='cli', args=['runserver'], default_map={464 'runserver': {465 'port': 5000466 }467 })Cleaned up context defaults and documented them.Armin Ronacherbefore adoption7d776de
lines 468–473why, one step back468469Context Defaults470----------------471472.. versionadded:: 2.0473Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde
line 474why, one step back474Starting with Click 2.0 you can override defaults for contexts not justCleaned up context defaults and documented them.Armin Ronacherbefore adoption7d776de
lines 475–484why, one step back475when 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 click484defaults -> settingsArmin Ronacherbefore adoption1bc0a19
line 485why, one step back485 CONTEXT_SETTINGS = dict(Cleaned up context defaults and documented them.Armin Ronacherbefore adoption7d776de
lines 486–488why, one step back486 default_map={'runserver': {'port': 5000}}487 )488defaults -> settingsArmin Ronacherbefore adoption1bc0a19
line 489why, one step back489 @click.group(context_settings=CONTEXT_SETTINGS)Cleaned up context defaults and documented them.Armin Ronacherbefore adoption7d776de
lines 490–505why, one step back490 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'])Added some docs on return values from commandsArmin Ronacherbefore adoptione413626
lines 506–552why, one step back506507508Command 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.