Skip to content
Myr

commands.rst

This file

Path

docs/commands.rst

303 lines · 8.9 KiB

Last changed by

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

History of this file

Take it

Initial commitArmin Ronacherbefore adoption4101de3

lines 1–20
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.14So if the script is the only command it will always fire (unless a15parameter callback prevents it. This for instance happens if someone16passes ``--help`` to the script).1718For groups and multi commands the situation looks different. In that case19the callback fires whenever a subcommand fires (unless this behavior is20changed). What this means in practice is that an outer command runs

More automated docsArmin Ronacherbefore adoption8254b79

line 21why, one step back
21when an inner command runs:

Initial commitArmin Ronacherbefore adoption4101de3

line 22
22

More automated docsArmin Ronacherbefore adoption8254b79

line 23why, one step back
23.. click:example::

Initial commitArmin Ronacherbefore adoption4101de3

lines 24–27
24
25 @click.group()26 @click.option('--debug/--no-debug', default=False)27 def cli(debug):

Implemented and exposed click.echoArmin Ronacherbefore adoption95c24b3

line 28why, one step back
28 click.echo('Debug mode is %s' % ('on' if debug else 'off'))

Initial commitArmin Ronacherbefore adoption4101de3

lines 29–31
29
30 @cli.command()31 def sync():

Implemented and exposed click.echoArmin Ronacherbefore adoption95c24b3

line 32why, one step back
32 click.echo('Synching')

Initial commitArmin Ronacherbefore adoption4101de3

line 33
33

More automated docsArmin Ronacherbefore adoption8254b79

line 34why, one step back
34Here is what this looks like:

Initial commitArmin Ronacherbefore adoption4101de3

line 35
35

More automated docsArmin Ronacherbefore adoption8254b79

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

Initial commitArmin Ronacherbefore adoption4101de3

line 37
37

More automated docsArmin Ronacherbefore adoption8254b79

lines 38–40why, one step back
38 invoke(cli, prog_name='tool.py')
39 println()40 invoke(cli, prog_name='tool.py', args=['--debug', 'sync'])

Initial commitArmin Ronacherbefore adoption4101de3

lines 41–49
41
42Nested Handling and Contexts43----------------------------4445As you can see from the earlier example the basic command group accepts a46debug argument which is passed to its callback, but not to the sync47command itself. The sync command only accepts its own arguments.4849This allows tools to act completely independent of each other. But how

Merge pull request #27 from epequeno/docs-editsArmin Ronacherbefore adoptionb2475cd

line 50why, one step back
50does one command talk to a nested one? The answer to this is the

Initial commitArmin Ronacherbefore adoption4101de3

lines 51–52
51:class:`Context`.
52

Merge pull request #27 from epequeno/docs-editsArmin Ronacherbefore adoptionb2475cd

line 53why, one step back
53Each time a command is invoked a new context is created and linked with the

Initial commitArmin Ronacherbefore adoption4101de3

lines 54–56
54parent context. Normally you can't see these contexts, but they are
55there. Contexts are passed to parameter callbacks together with the56value automatically. Commands can also ask for the context to be passed

Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68

lines 57–58why, one step back
57by marking themselves with the :func:`pass_context` decorator. In that
58case the context is passed as first argument.

Initial commitArmin Ronacherbefore adoption4101de3

lines 59–61
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 a

More automated docsArmin Ronacherbefore adoption8254b79

line 62why, one step back
62script like this:

Initial commitArmin Ronacherbefore adoption4101de3

line 63
63

More automated docsArmin Ronacherbefore adoption8254b79

line 64why, one step back
64.. click:example::

Initial commitArmin Ronacherbefore adoption4101de3

line 65
65

Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68

line 66why, one step back
66 @click.group()

Initial commitArmin Ronacherbefore adoption4101de3

line 67
67 @click.option('--debug/--no-debug', default=False)

Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68

line 68why, one step back
68 @click.pass_context

Initial commitArmin Ronacherbefore adoption4101de3

lines 69–71
69 def cli(ctx, debug):
70 ctx.obj['DEBUG'] = debug71

Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68

lines 72–73why, one step back
72 @cli.command()
73 @click.pass_context

Initial commitArmin Ronacherbefore adoption4101de3

line 74
74 def sync(ctx):

Implemented and exposed click.echoArmin Ronacherbefore adoption95c24b3

line 75why, one step back
75 click.echo('Debug is %s' % (ctx.obj['DEBUG'] and 'on' or 'off'))

Initial commitArmin Ronacherbefore adoption4101de3

lines 76–80
76
77 if __name__ == '__main__':78 cli(obj={})7980If the object is provided each context will pass the object onwards to

Merge pull request #21 from julen/doc-fixesArmin Ronacherbefore adoptiona4b7d70

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

Initial commitArmin Ronacherbefore adoption4101de3

lines 82–87
82reach to a parent ``context.parent`` can be used.
8384In addition to that instead of passing an object down nothing stops the85application from modifying global state. For instance you could just flip86a global ``DEBUG`` variable and be done with it.87

Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68

lines 88–102why, one step back
88Decorating Commands
89-------------------9091As you have seen in the earlier example a decorator can change how a92command is invoked. What actually happens behind the scenes is that93callbacks 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. For98instance a common pattern would be to configure an object representing99state and then storing it on the context and then to use a custom100decorator to find the most recent object of this sort and pass it as first101argument.102

More automated docsArmin Ronacherbefore adoption8254b79

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

Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68

line 104why, one step back
104

More automated docsArmin Ronacherbefore adoption8254b79

lines 105–106why, one step back
105.. click:example::
106

Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68

lines 107–123why, one step back
107 from functools import update_wrapper
108109 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 function116in the correct way. So the function will either be called with ``f(ctx,117obj)`` or ``f(obj)`` depending on if it itself is decorated with118: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.122123

Initial commitArmin Ronacherbefore adoption4101de3

lines 124–134
124Group Invocation Without Command
125--------------------------------126127By default a group or multi command is not invoked unless a subcommand is128passed. In fact, not providing a command automatically passes ``--help``129by default. This behavior can be changed by passing130``invoke_without_command=True`` to a group. In that case the callback is131always invoked instead of showing the help page. The context object also132includes information about if the invocation would go to a subcommand or133not.134

More automated docsArmin Ronacherbefore adoption8254b79

line 135why, one step back
135Example:

Initial commitArmin Ronacherbefore adoption4101de3

line 136
136

More automated docsArmin Ronacherbefore adoption8254b79

line 137why, one step back
137.. click:example::

Initial commitArmin Ronacherbefore adoption4101de3

line 138
138

Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68

lines 139–140why, one step back
139 @click.group(invoke_without_command=True)
140 @click.pass_context

Initial commitArmin Ronacherbefore adoption4101de3

lines 141–142
141 def cli(ctx):
142 if ctx.invoked_subcommand is None:

Implemented and exposed click.echoArmin Ronacherbefore adoption95c24b3

line 143why, one step back
143 click.echo('I was invoked without subcommand')

Initial commitArmin Ronacherbefore adoption4101de3

line 144
144 else:

Implemented and exposed click.echoArmin Ronacherbefore adoption95c24b3

line 145why, one step back
145 click.echo('I am about to invoke %s' % ctx.invoked_subcommand)

Initial commitArmin Ronacherbefore adoption4101de3

lines 146–148
146
147 @cli.command()148 def sync():

Implemented and exposed click.echoArmin Ronacherbefore adoption95c24b3

line 149why, one step back
149 click.echo('The subcommand')

Initial commitArmin Ronacherbefore adoption4101de3

lines 150–158
150
151And how it works in practice::152153 $ python tool.py 154 I was invoked without subcommand155 $ python tool.py sync156 I am about to invoke sync157 The subcommand158

Added an example for aliasesArmin Ronacherbefore adoptione2d388e

lines 159–160why, one step back
159.. _custom-multi-commands:
160

Initial commitArmin Ronacherbefore adoption4101de3

lines 161–167
161Custom Multi Commands
162---------------------163164In addition to using :func:`click.group` you can also build your own165custom multi commands. This is useful when you want to support commands166being loaded lazily from plugins.167

More automated docsArmin Ronacherbefore adoption8254b79

line 168why, one step back
168A custom multi command just needs to implement a list and load method:

Initial commitArmin Ronacherbefore adoption4101de3

line 169
169

More automated docsArmin Ronacherbefore adoption8254b79

lines 170–171why, one step back
170.. click:example::
171

Initial commitArmin Ronacherbefore adoption4101de3

lines 172–178
172 import click
173 import os174175 plugin_folder = os.path.join(os.path.dirname(__file__), 'commands')176177 class MyCLI(click.MultiCommand):178

Some small fixes for problemsArmin Ronacherbefore adoption8f7caca

line 179why, one step back
179 def list_commands(self, ctx):

Initial commitArmin Ronacherbefore adoption4101de3

lines 180–199
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 rv186187 def get_command(self, name):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()

Added an example for aliasesArmin Ronacherbefore adoptione2d388e

line 200why, one step back
200

More automated docsArmin Ronacherbefore adoption8254b79

lines 201–203why, one step back
201These custom classes can also be used with decorators:
202203.. click:example::

Added an example for aliasesArmin Ronacherbefore adoptione2d388e

lines 204–207why, one step back
204
205 @click.command(cls=MyCLI)206 def cli():207 pass

Implemented basic command collectionsArmin Ronacherbefore adoption055a8e6

lines 208–218why, one step back
208
209Merging Multi Commands210----------------------211212In addition to implementing custom multi commands it can also be213interesting to merge multiple together into one script. While this is214generally not as recommended as nesting one below the other the merging215approach 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 #58 from julen/doc-fixesArmin Ronacherbefore adoption45be1ca

lines 219–221why, one step back
219commands and makes the commands available on the same class. It accepts a
220list of other multi commands and makes the commands available on the same221level.

Implemented basic command collectionsArmin Ronacherbefore adoption055a8e6

lines 222–256why, one step back
222
223Example usage:224225.. click:example::226227 import click228229 @click.group()230 def cli1():231 pass232233 @cli1.command()234 def cmd1():235 """Command on cli1"""236237 @click.group()238 def cli2():239 pass240241 @cli1.command()242 def cmd2():243 """Command on cli2"""244245 cli = click.CommandCollection(sources=[cli1, cli2])246247 if __name__ == '__main__':248 cli()249250And what it looks like:251252.. click:run::253254 invoke(cli, prog_name='cli', args=['--help'])255256In case a command exists on more than one source, the first source wins.

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

lines 257–303why, one step back
257
258Overriding Defaults259-------------------260261By default the default value for a parameter is pulled from the262``default`` flag that is provided when it's defined. But that's not the263only place defaults can be loaded from. The other place is the264:attr:`Context.default_map` (a dictionary) on the context. This allows265defaults to be loaded from a config file to override the regular defaults.266267This is useful if you plug in some commands from another package but268you're not satisfied with the defaults.269270The default map can be nested arbitrarily for each subcommand and be271provided when the script is invoked. Alternatively it can also be272overriden at any point by commands. For instance a toplevel command could273load the defaults from a config file.274275Example usage:276277.. click:example::278279 import click280281 @click.group()282 def cli():283 pass284285 @cli.command()286 @click.option('--port', default=8000)287 def runserver(port):288 click.echo('Serving on http://127.0.0.1:%d/' % port)289290 if __name__ == '__main__':291 cli(default_map={292 'runserver': {293 'port': 5000294 }295 })296297.. click:run::298299 invoke(cli, prog_name='cli', args=['runserver'], default_map={300 'runserver': {301 'port': 5000302 }303 })