Skip to content
Myr

Fill in a lot of missing command and group docs.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Edward G · committed by Edward G · parent 8a47580 · Browse files · 5 files+292 added−117 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+292 added−117 removed

  • other:+292 added−117 removed

5 files+292 added−117 removed

modified:docs/advanced.rst+63 added
5 unmodified lines
6In addition to common functionality that is implemented in the library7itself, there are countless patterns that can be implemented by extending8Click. This page should give some insight into what can be accomplished.910.. contents::11 :depth: 112 :local:1314.. _custom-groups:1516Custom Groups17-------------1819You can customize the behavior of a group beyond the arguments it accepts by20subclassing :class:`click.Group`.2122The most common methods to override are :meth:`~click.Group.get_command` and23:meth:`~click.Group.list_commands`.2425The following example implements a basic plugin system that loads commands from26Python files in a folder. The command is lazily loaded to avoid slow startup.2728.. code-block:: python2930 import importlib.util31 import os32 import click3334 class PluginGroup(click.Group):35 def __init__(self, name=None, plugin_folder="commands", **kwargs):36 super().__init__(name=name, **kwargs)37 self.plugin_folder = plugin_folder3839 def list_commands(self, ctx):40 rv = []4142 for filename in os.listdir(self.plugin_folder):43 if filename.endswith(".py"):44 rv.append(filename[:-3])4546 rv.sort()47 return rv4849 def get_command(self, ctx, name):50 path = os.path.join(self.plugin_folder, f"{name}.py")51 spec = importlib.util.spec_from_file_location(name, path)52 module = importlib.util.module_from_spec(spec)53 spec.loader.exec_module(module)54 return module.cli5556 cli = PluginGroup(57 plugin_folder=os.path.join(os.path.dirname(__file__), "commands")58 )5960 if __name__ == "__main__":61 cli()6263Custom classes can also be used with decorators:6465.. code-block:: python6667 @click.group(68 cls=PluginGroup,69 plugin_folder=os.path.join(os.path.dirname(__file__), "commands")70 )71 def cli():72 pass7374.. _aliases:7576Command Aliases77---------------
487 unmodified lines
added:docs/commands-and-groups.rst+220 added
1Basic Commands, Groups, Context2================================34.. currentmodule:: click56Commands and Groups are the building blocks for Click applications. :class:`Command` wraps a function to make it into a cli command. :class:`Group` wraps Commands and Groups to make them into applications. :class:`Context` is how groups and commands communicate.78.. contents::9 :depth: 110 :local:1112Basic Command Example13----------------------14A simple command decorator takes no arguments.1516.. click:example::17 @click.command()18 @click.option('--count', default=1)19 def hello(count):20 for x in range(count):21 click.echo("Hello!")2223.. click:run::24 invoke(hello, args=['--count', '2',])2526Renaming Commands27------------------28By default the command is the function name with underscores replaced by dashes. To change this pass the desired name into the first positional argument.2930.. click:example::31 @click.command('say-hello')32 @click.option('--count', default=1)33 def hello(count):34 for x in range(count):35 click.echo("Hello!")3637.. click:run::38 invoke(hello, args=['--count', '2',])3940Deprecating Commands41---------------------42To mark a command as deprecated pass in ``deprecated=True``4344.. click:example::45 @click.command('say-hello', deprecated=True)46 @click.option('--count', default=1)47 def hello(count):48 for x in range(count):49 click.echo("Hello!")5051.. click:run::52 invoke(hello, args=['--count', '2',])5354Basic Group Example55---------------------56A group wraps command(s). After being wrapped, the commands are nested under that group. You can see that on the help pages and in the execution. By default, invoking the group with no command shows the help page.5758.. click:example::59 @click.group()60 def greeting():61 click.echo('Starting greeting ...')6263 @greeting.command('say-hello')64 @click.option('--count', default=1)65 def hello(count):66 for x in range(count):67 click.echo("Hello!")6869At the top level:7071.. click:run::7273 invoke(greeting)7475At the command level:7677.. click:run::7879 invoke(greeting, args=['say-hello'])80 invoke(greeting, args=['say-hello', '--help'])8182As you can see from the above example, the function wrapped by the group decorator executes unless it is interrupted (for example by calling the help).8384Renaming Groups85-----------------86To have a name other than the decorated function name as the group name, pass it in as the first positional argument.8788.. click:example::89 @click.group('greet_someone')90 def greeting():91 click.echo('Starting greeting ...')9293 @greeting.command('say-hello')94 @click.option('--count', default=1)95 def hello(count):96 for x in range(count):97 click.echo("Hello!")9899.. click:run::100101 invoke(greeting, args=['say-hello'])102103Group Invocation Without Command104--------------------------------105106By default, a group is not invoked unless a subcommand is passed. In fact, not107providing a command automatically passes ``--help`` by default. This behavior108can be changed by passing ``invoke_without_command=True`` to a group. In that109case, the callback is always invoked instead of showing the help page. The110context object also includes information about whether or not the invocation111would go to a subcommand.112113.. click:example::114115 @click.group(invoke_without_command=True)116 @click.pass_context117 def cli(ctx):118 if ctx.invoked_subcommand is None:119 click.echo('I was invoked without subcommand')120 else:121 click.echo(f"I am about to invoke {ctx.invoked_subcommand}")122123 @cli.command()124 def sync():125 click.echo('The subcommand')126127.. click:run::128129 invoke(cli, prog_name='tool', args=[])130 invoke(cli, prog_name='tool', args=['sync'])131132133134Group Separation135--------------------------136Within a group, command :ref:`parameters` attached to a command belong only to that command.137138.. click:example::139 @click.group()140 def greeting():141 pass142143 @greeting.command()144 @click.option('--count', default=1)145 def hello(count):146 for x in range(count):147 click.echo("Hello!")148149 @greeting.command()150 @click.option('--count', default=1)151 def goodbye(count):152 for x in range(count):153 click.echo("Goodbye!")154155.. click:run::156157 invoke(greeting, args=['hello', '--count', '2'])158 invoke(greeting, args=['goodbye', '--count', '2'])159 invoke(greeting)160161Additionally parameters for a given group belong only to that group and not to the commands under it. What this means is that options and arguments for a specific command have to be specified *after* the command name itself, but *before* any other command names.162163This behavior is observable with the ``--help`` option. Suppose we have a group called ``tool`` containing a command called ``sub``.164165- ``tool --help`` returns the help for the whole program (listing subcommands).166- ``tool sub --help`` returns the help for the ``sub`` subcommand.167- But ``tool.py --help sub`` treats ``--help`` as an argument for the main program. Click then invokes the callback for ``--help``, which prints the help and aborts the program before click can process the subcommand.168169Arbitrary Nesting170------------------171Commands are attached to a group. Multiple groups can be attached to another group. Groups containing multiple groups can be attached to a group, and so on.172To invoke a command nest under multiple groups, all the above groups must added.173174.. click:example::175176 @click.group()177 def cli():178 pass179180 # Not @click so that the group is registered now.181 @cli.group()182 def session():183 click.echo('Starting session')184185 @session.command()186 def initdb():187 click.echo('Initialized the database')188189 @session.command()190 def dropdb():191 click.echo('Dropped the database')192193.. click:run::194195 invoke(cli, args=['session', 'initdb'])196197Lazily Attaching Commands198--------------------------199Most examples so far have attached the the commands and group immediately, but commands may be registered later. This could be used to split command into multiple Python modules.200201.. click:example::202203 @click.group()204 def cli():205 pass206207 @click.command()208 def initdb():209 click.echo('Initialized the database')210211 @click.command()212 def dropdb():213 click.echo('Dropped the database')214215 cli.add_command(initdb)216 cli.add_command(dropdb)217218Context Object219-------------------220The :class:`Context` object ...
modified:docs/commands.rst+6 added-117 removed
1Commands and Groups2===================1Advanced Groups and Context2=============================34.. currentmodule:: click56The structure of a Click application is defined with :class:`Command`, which7defines an individual named command, and :class:`Group`, which defines a nested8collection of commands (or more groups) under a name.6In addition to the capabilities covered in the previous section, Groups have more advanced capabilities that leverage the Context.78.. contents::9 :depth: 110 :local:1112Callback Invocation13-------------------14
24 unmodified lines
39 invoke(cli, prog_name='tool.py')40 println()41 invoke(cli, prog_name='tool.py', args=['--debug', 'sync'])4242Passing 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.6143Nested Handling and Contexts44----------------------------4546As you can see from the earlier example, the basic command group accepts a
77 unmodified lines
124125This is a very powerful concept that can be used to build very complex126nested applications; see :ref:`complex-guide` for more information.127147148Group Invocation Without Command149--------------------------------150151By default, a group is not invoked unless a subcommand is passed. In fact, not152providing a command automatically passes ``--help`` by default. This behavior153can be changed by passing ``invoke_without_command=True`` to a group. In that154case, the callback is always invoked instead of showing the help page. The155context object also includes information about whether or not the invocation156would go to a subcommand.157158.. click:example::159160 @click.group(invoke_without_command=True)161 @click.pass_context162 def cli(ctx):163 if ctx.invoked_subcommand is None:164 click.echo('I was invoked without subcommand')165 else:166 click.echo(f"I am about to invoke {ctx.invoked_subcommand}")167168 @cli.command()169 def sync():170 click.echo('The subcommand')171172.. click:run::173174 invoke(cli, prog_name='tool', args=[])175 invoke(cli, prog_name='tool', args=['sync'])176177178.. _custom-groups:179180Custom Groups181-------------182183You can customize the behavior of a group beyond the arguments it accepts by184subclassing :class:`click.Group`.185186The most common methods to override are :meth:`~click.Group.get_command` and187:meth:`~click.Group.list_commands`.188189The following example implements a basic plugin system that loads commands from190Python files in a folder. The command is lazily loaded to avoid slow startup.191192.. code-block:: python193194 import importlib.util195 import os196 import click197198 class PluginGroup(click.Group):199 def __init__(self, name=None, plugin_folder="commands", **kwargs):200 super().__init__(name=name, **kwargs)201 self.plugin_folder = plugin_folder202203 def list_commands(self, ctx):204 rv = []205206 for filename in os.listdir(self.plugin_folder):207 if filename.endswith(".py"):208 rv.append(filename[:-3])209210 rv.sort()211 return rv212213 def get_command(self, ctx, name):214 path = os.path.join(self.plugin_folder, f"{name}.py")215 spec = importlib.util.spec_from_file_location(name, path)216 module = importlib.util.module_from_spec(spec)217 spec.loader.exec_module(module)218 return module.cli219220 cli = PluginGroup(221 plugin_folder=os.path.join(os.path.dirname(__file__), "commands")222 )223224 if __name__ == "__main__":225 cli()226227Custom classes can also be used with decorators:228229.. code-block:: python230231 @click.group(232 cls=PluginGroup,233 plugin_folder=os.path.join(os.path.dirname(__file__), "commands")234 )235 def cli():236 pass237238128.. _command-chaining:129130Command Chaining131----------------
297 unmodified lines
modified:docs/index.rst+1 added
72 unmodified lines
73 setuptools74 parameters75 arguments76 options77 commands-and-groups78 commands79 documentation80 prompts81 complex
28 unmodified lines
modified:docs/parameters.rst+2 added
1.. _parameters:23Parameters4==========56.. currentmodule:: click
133 unmodified lines