Skip to content
Myr

commands.rst

This file

Path

docs/commands.rst

302 lines · 8.8 KiB

Last changed by

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

History of this file

Take it

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

Merge pull request #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

lines 1–12why, 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-------------------12

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

lines 13–15why, one step back
13For a regular command, the callback is executed whenever the command runs.
14If the script is the only command it will always fire (unless a15parameter callback prevents it). This for instance happens if someone

Merge pull request #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

lines 16–17why, one step back
16passes ``--help`` to the script).
17

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 18why, one step back
18For groups and multi commands, the situation looks different. In this case,

Merge pull request #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

lines 19–44why, one step back
19the callback fires whenever a subcommand fires (unless this behavior is
20changed). 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'])4142Nested Handling and Contexts43----------------------------44

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 45why, one step back
45As you can see from the earlier example, the basic command group accepts a

Merge pull request #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

lines 46–48why, one step back
46debug argument which is passed to its callback, but not to the sync
47command itself. The sync command only accepts its own arguments.48

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 49why, one step back
49This allows tools to act completely independent of each other, but how

Merge pull request #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

lines 50–52why, one step back
50does one command talk to a nested one? The answer to this is the
51:class:`Context`.52

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

lines 53–54why, one step back
53Each time a command is invoked, a new context is created and linked with the
54parent context. Normally, you can't see these contexts, but they are

Merge pull request #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

lines 55–57why, one step back
55there. Contexts are passed to parameter callbacks together with the
56value automatically. Commands can also ask for the context to be passed57by marking themselves with the :func:`pass_context` decorator. In that

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 58why, one step back
58case, the context is passed as first argument.

Merge pull request #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

lines 59–79why, one step back
59
60The context can also carry a program specified object that can be61used for the program's purposes. What this means is that you can build a62script like this:6364.. click:example::6566 @click.group()67 @click.option('--debug/--no-debug', default=False)68 @click.pass_context69 def cli(ctx, debug):70 ctx.obj['DEBUG'] = debug7172 @cli.command()73 @click.pass_context74 def sync(ctx):75 click.echo('Debug is %s' % (ctx.obj['DEBUG'] and 'on' or 'off'))7677 if __name__ == '__main__':78 cli(obj={})79

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 80why, one step back
80If the object is provided, each context will pass the object onwards to

Merge pull request #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

line 81why, one step back
81its children, but at any level a context's object can be overridden. To

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 82why, one step back
82reach to a parent, ``context.parent`` can be used.

Merge pull request #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

line 83why, one step back
83

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

lines 84–85why, one step back
84In addition to that, instead of passing an object down, nothing stops the
85application from modifying global state. For instance, you could just flip

Merge pull request #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

lines 86–90why, one step back
86a global ``DEBUG`` variable and be done with it.
8788Decorating Commands89-------------------90

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 91why, one step back
91As you have seen in the earlier example, a decorator can change how a

Merge pull request #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

lines 92–97why, one step back
92command is invoked. What actually happens behind the scenes is that
93callbacks are always invoked through the :meth:`Context.invoke` method94which automatically invokes a command correctly (by either passing the95context or not).9697This is very useful when you want to write custom decorators. For

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 98why, one step back
98instance, a common pattern would be to configure an object representing

Merge pull request #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

lines 99–102why, one step back
99state and then storing it on the context and then to use a custom
100decorator to find the most recent object of this sort and pass it as first101argument.102

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 103why, one step back
103For instance, the :func:`pass_obj` decorator can be implemented like this:

Merge pull request #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

lines 104–115why, one step back
104
105.. click:example::106107 from functools import update_wrapper108109 def pass_obj(f):110 @click.pass_context111 def new_func(ctx, *args, **kwargs):112 return ctx.invoke(f, ctx.obj, *args, **kwargs)113 return update_wrapper(new_func, f)114115The :meth:`Context.invoke` command will automatically invoke the function

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 116why, one step back
116in the correct way, so the function will either be called with ``f(ctx,

Merge pull request #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

lines 117–126why, one step back
117obj)`` or ``f(obj)`` depending on if it itself is decorated with
118:func:`with_context`.119120This is a very powerful context that can be used to build very complex121nested applications. See :ref:`complex-guide` for more information.122123124Group Invocation Without Command125--------------------------------126

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 127why, one step back
127By default, a group or multi command is not invoked unless a subcommand is

Merge pull request #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

lines 128–129why, one step back
128passed. In fact, not providing a command automatically passes ``--help``
129by default. This behavior can be changed by passing

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 130why, one step back
130``invoke_without_command=True`` to a group. In that case, the callback is

Merge pull request #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

line 131why, one step back
131always invoked instead of showing the help page. The context object also

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

lines 132–133why, one step back
132includes information about whether or not the invocation would go to a
133subcommand.

Merge pull request #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

lines 134–152why, one step back
134
135Example:136137.. click:example::138139 @click.group(invoke_without_command=True)140 @click.pass_context141 def cli(ctx):142 if ctx.invoked_subcommand is None:143 click.echo('I was invoked without subcommand')144 else:145 click.echo('I am about to invoke %s' % ctx.invoked_subcommand)146147 @cli.command()148 def sync():149 click.echo('The subcommand')150151And how it works in practice::152

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 153why, one step back
153 $ python tool.py

Merge pull request #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

lines 154–163why, one step back
154 I was invoked without subcommand
155 $ python tool.py sync156 I am about to invoke sync157 The subcommand158159.. _custom-multi-commands:160161Custom Multi Commands162---------------------163

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 164why, one step back
164In addition to using :func:`click.group`, you can also build your own

Merge pull request #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

lines 165–186why, one step back
165custom multi commands. This is useful when you want to support commands
166being loaded lazily from plugins.167168A custom multi command just needs to implement a list and load method:169170.. click:example::171172 import click173 import os174175 plugin_folder = os.path.join(os.path.dirname(__file__), 'commands')176177 class MyCLI(click.MultiCommand):178179 def list_commands(self, ctx):180 rv = []181 for filename in os.listdir(plugin_folder):182 if filename.endswith('.py'):183 rv.append(filename[:-3])184 rv.sort()185 return rv186

Fixed a broken exampleArmin Ronacherbefore adoptiona2c58d5

line 187why, one step back
187 def get_command(self, ctx, name):

Merge pull request #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

lines 188–211why, one step back
188 ns = {}
189 fn = os.path.join(plugin_folder, name + '.py')190 with open(fn) as f:191 code = compile(f.read(), fn, 'exec')192 eval(code, ns, ns)193 return ns['cli']194195 cli = MyCLI(help='This tool\'s subcommands are loaded from a '196 'plugin folder dynamically.')197198 if __name__ == '__main__':199 cli()200201These custom classes can also be used with decorators:202203.. click:example::204205 @click.command(cls=MyCLI)206 def cli():207 pass208209Merging Multi Commands210----------------------211

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 212why, one step back
212In addition to implementing custom multi commands, it can also be

Merge pull request #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

line 213why, one step back
213interesting to merge multiple together into one script. While this is

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 214why, one step back
214generally not as recommended as nesting one below the other, the merging

Merge pull request #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

lines 215–218why, one step back
215approach can be useful in some circumstances for a nicer shell experience.
216217A default implementation for such a merging system is the218:class:`CommandCollection` class. It accepts a list of other multi

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 219why, one step back
219commands and makes the commands available on the same level.

Merge pull request #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

lines 220–238why, one step back
220
221Example usage:222223.. click:example::224225 import click226227 @click.group()228 def cli1():229 pass230231 @cli1.command()232 def cmd1():233 """Command on cli1"""234235 @click.group()236 def cli2():237 pass238

Merge pull request #99 from jezenielzapanta/patch-1Armin Ronacherbefore adoption73c1528

line 239why, one step back
239 @cli2.command()

Merge pull request #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

lines 240–253why, one step back
240 def cmd2():
241 """Command on cli2"""242243 cli = click.CommandCollection(sources=[cli1, cli2])244245 if __name__ == '__main__':246 cli()247248And what it looks like:249250.. click:run::251252 invoke(cli, prog_name='cli', args=['--help'])253

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

line 254why, one step back
254In case a command exists in more than one source, the first source wins.

Added support for default overrides. This fixes #42Armin Ronacherbefore adoptione77783d

lines 255–258why, one step back
255
256Overriding Defaults257-------------------258

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

lines 259–260why, one step back
259By default, the default value for a parameter is pulled from the
260``default`` flag that is provided when it's defined, but that's not the

Added support for default overrides. This fixes #42Armin Ronacherbefore adoptione77783d

lines 261–262why, one step back
261only place defaults can be loaded from. The other place is the
262:attr:`Context.default_map` (a dictionary) on the context. This allows

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

lines 263–264why, one step back
263defaults to be loaded from a configuration file to override the regular
264defaults.

Added support for default overrides. This fixes #42Armin Ronacherbefore adoptione77783d

lines 265–269why, one step back
265
266This is useful if you plug in some commands from another package but267you're not satisfied with the defaults.268269The default map can be nested arbitrarily for each subcommand and be

Merge pull request #109 from iKevinY/doc-fixesArmin Ronacherbefore adoptiond428e69

lines 270–272why, one step back
270provided when the script is invoked. Alternatively, it can also be
271overriden at any point by commands. For instance a top-level command could272load the defaults from a configuration file.

Added support for default overrides. This fixes #42Armin Ronacherbefore adoptione77783d

lines 273–302why, one step back
273
274Example usage:275276.. click:example::277278 import click279280 @click.group()281 def cli():282 pass283284 @cli.command()285 @click.option('--port', default=8000)286 def runserver(port):287 click.echo('Serving on http://127.0.0.1:%d/' % port)288289 if __name__ == '__main__':290 cli(default_map={291 'runserver': {292 'port': 5000293 }294 })295296.. click:run::297298 invoke(cli, prog_name='cli', args=['runserver'], default_map={299 'runserver': {300 'port': 5000301 }302 })