Skip to content
Myr

commands.rst

This file

Path

docs/commands.rst

216 lines · 6.6 KiB

Last changed by

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

History of this file

Take it

Initial commitArmin Ronacherbefore adoption4101de3

lines 1–60
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 runs21when an inner command runs::2223 import click2425 @click.group()26 @click.option('--debug/--no-debug', default=False)27 def cli(debug):28 print('Debug mode is %s' % ('on' if debug else 'off'))2930 @cli.command()31 def sync():32 print('Synching')3334 if __name__ == '__main__':35 cli()3637Here is what this looks like::3839 $ python tool.py40 Usage: tool.py [OPTIONS] COMMAND [ARGS]...4142 Commands:43 sync 4445 Options:46 --debug / --no-debug 47 --help Show this message and exit.48 49 $ python tool.py --debug sync50 Debug mode is on51 Synching 5253Nested Handling and Contexts54----------------------------5556As you can see from the earlier example the basic command group accepts a57debug argument which is passed to its callback, but not to the sync58command itself. The sync command only accepts its own arguments.5960This allows tools to act completely independent of each other. But how

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

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

Initial commitArmin Ronacherbefore adoption4101de3

lines 62–63
62:class:`Context`.
63

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

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

Initial commitArmin Ronacherbefore adoption4101de3

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

Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68

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

Initial commitArmin Ronacherbefore adoption4101de3

lines 70–76
70
71The context can also carry a program specified object that can be72used for the program's purposes. What this means is that you can build a73script like this::7475 import click76

Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68

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

Initial commitArmin Ronacherbefore adoption4101de3

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

Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68

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

Initial commitArmin Ronacherbefore adoption4101de3

lines 80–82
80 def cli(ctx, debug):
81 ctx.obj['DEBUG'] = debug82

Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68

lines 83–84why, one step back
83 @cli.command()
84 @click.pass_context

Initial commitArmin Ronacherbefore adoption4101de3

lines 85–91
85 def sync(ctx):
86 print('Debug is %s' % (ctx.obj['DEBUG'] and 'on' or 'off'))8788 if __name__ == '__main__':89 cli(obj={})9091If the object is provided each context will pass the object onwards to

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

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

Initial commitArmin Ronacherbefore adoption4101de3

lines 93–98
93reach to a parent ``context.parent`` can be used.
9495In addition to that instead of passing an object down nothing stops the96application from modifying global state. For instance you could just flip97a global ``DEBUG`` variable and be done with it.98

Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68

lines 99–133why, one step back
99Decorating Commands
100-------------------101102As you have seen in the earlier example a decorator can change how a103command is invoked. What actually happens behind the scenes is that104callbacks are always invoked through the :meth:`Context.invoke` method105which automatically invokes a command correctly (by either passing the106context or not).107108This is very useful when you want to write custom decorators. For109instance a common pattern would be to configure an object representing110state and then storing it on the context and then to use a custom111decorator to find the most recent object of this sort and pass it as first112argument.113114For instance the :func:`pass_obj` decorator can be implemented like this::115116 import click117 from functools import update_wrapper118119 def pass_obj(f):120 @click.pass_context121 def new_func(ctx, *args, **kwargs):122 return ctx.invoke(f, ctx.obj, *args, **kwargs)123 return update_wrapper(new_func, f)124125The :meth:`Context.invoke` command will automatically invoke the function126in the correct way. So the function will either be called with ``f(ctx,127obj)`` or ``f(obj)`` depending on if it itself is decorated with128:func:`with_context`.129130This is a very powerful context that can be used to build very complex131nested applications. See :ref:`complex-guide` for more information.132133

Initial commitArmin Ronacherbefore adoption4101de3

lines 134–148
134Group Invocation Without Command
135--------------------------------136137By default a group or multi command is not invoked unless a subcommand is138passed. In fact, not providing a command automatically passes ``--help``139by default. This behavior can be changed by passing140``invoke_without_command=True`` to a group. In that case the callback is141always invoked instead of showing the help page. The context object also142includes information about if the invocation would go to a subcommand or143not.144145Example::146147 import click148

Added docs for building complex click applicationsArmin Ronacherbefore adoption23d3f68

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

Initial commitArmin Ronacherbefore adoption4101de3

lines 151–171
151 def cli(ctx):
152 if ctx.invoked_subcommand is None:153 print('I was invoked without subcommand')154 else:155 print('I am about to invoke %s' % ctx.invoked_subcommand)156157 @cli.command()158 def sync():159 print('The subcommand')160161 if __name__ == '__main__':162 cli()163164And how it works in practice::165166 $ python tool.py 167 I was invoked without subcommand168 $ python tool.py sync169 I am about to invoke sync170 The subcommand171

Added an example for aliasesArmin Ronacherbefore adoptione2d388e

lines 172–173why, one step back
172.. _custom-multi-commands:
173

Initial commitArmin Ronacherbefore adoption4101de3

lines 174–210
174Custom Multi Commands
175---------------------176177In addition to using :func:`click.group` you can also build your own178custom multi commands. This is useful when you want to support commands179being loaded lazily from plugins.180181A custom multi command just needs to implement a list and load method::182183 import click184 import os185186 plugin_folder = os.path.join(os.path.dirname(__file__), 'commands')187188 class MyCLI(click.MultiCommand):189190 def list_commands(self):191 rv = []192 for filename in os.listdir(plugin_folder):193 if filename.endswith('.py'):194 rv.append(filename[:-3])195 rv.sort()196 return rv197198 def get_command(self, name):199 ns = {}200 fn = os.path.join(plugin_folder, name + '.py')201 with open(fn) as f:202 code = compile(f.read(), fn, 'exec')203 eval(code, ns, ns)204 return ns['cli']205206 cli = MyCLI(help='This tool\'s subcommands are loaded from a '207 'plugin folder dynamically.')208209 if __name__ == '__main__':210 cli()

Added an example for aliasesArmin Ronacherbefore adoptione2d388e

lines 211–216why, one step back
211
212These custom classes can also be used with decorators::213214 @click.command(cls=MyCLI)215 def cli():216 pass