Skip to content
Myr

Make distinct sections for advanced patterns and extending click.

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 937c68d · Browse files · 6 files+298 added−269 removed
This commit

State

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

Diff stats

6 files+298 added−269 removed

  • other:+298 added−269 removed

6 files+298 added−269 removed

modified:docs/advanced.rst+2 added-257 removed
1 unmodified line
2=================34.. currentmodule:: click56In 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.6In addition to common functionality, Click offers some advanced features.78.. contents::11 :depth: 29 :depth: 110 :local:1112Callbacks and Eager Options13---------------------------
93 unmodified lines
107 invoke(roll, args=["--rolls=2d12"])108 println()109 invoke(roll, input=["42", "2d12"])110113.. _custom-groups:114115Custom Groups116-------------117118You can customize the behavior of a group beyond the arguments it accepts by119subclassing :class:`click.Group`.120121The most common methods to override are :meth:`~click.Group.get_command` and122:meth:`~click.Group.list_commands`.123124The following example implements a basic plugin system that loads commands from125Python files in a folder. The command is lazily loaded to avoid slow startup.126127.. code-block:: python128129 import importlib.util130 import os131 import click132133 class PluginGroup(click.Group):134 def __init__(self, name=None, plugin_folder="commands", **kwargs):135 super().__init__(name=name, **kwargs)136 self.plugin_folder = plugin_folder137138 def list_commands(self, ctx):139 rv = []140141 for filename in os.listdir(self.plugin_folder):142 if filename.endswith(".py"):143 rv.append(filename[:-3])144145 rv.sort()146 return rv147148 def get_command(self, ctx, name):149 path = os.path.join(self.plugin_folder, f"{name}.py")150 spec = importlib.util.spec_from_file_location(name, path)151 module = importlib.util.module_from_spec(spec)152 spec.loader.exec_module(module)153 return module.cli154155 cli = PluginGroup(156 plugin_folder=os.path.join(os.path.dirname(__file__), "commands")157 )158159 if __name__ == "__main__":160 cli()161162Custom classes can also be used with decorators:163164.. code-block:: python165166 @click.group(167 cls=PluginGroup,168 plugin_folder=os.path.join(os.path.dirname(__file__), "commands")169 )170 def cli():171 pass172173.. _aliases:174175Command Aliases176---------------177178Many tools support aliases for commands. For example, you can configure179``git`` to accept ``git ci`` as alias for ``git commit``. Other tools also180support auto-discovery for aliases by automatically shortening them.181182It's possible to customize :class:`Group` to provide this functionality. As183explained in :ref:`custom-groups`, a group provides two methods:184:meth:`~Group.list_commands` and :meth:`~Group.get_command`. In this particular185case, you only need to override the latter as you generally don't want to186enumerate the aliases on the help page in order to avoid confusion.187188The following example implements a subclass of :class:`Group` that accepts a189prefix for a command. If there was a command called ``push``, it would accept190``pus`` as an alias (so long as it was unique):191192.. click:example::193194 class AliasedGroup(click.Group):195 def get_command(self, ctx, cmd_name):196 rv = super().get_command(ctx, cmd_name)197198 if rv is not None:199 return rv200201 matches = [202 x for x in self.list_commands(ctx)203 if x.startswith(cmd_name)204 ]205206 if not matches:207 return None208209 if len(matches) == 1:210 return click.Group.get_command(self, ctx, matches[0])211212 ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")213214 def resolve_command(self, ctx, args):215 # always return the full command name216 _, cmd, args = super().resolve_command(ctx, args)217 return cmd.name, cmd, args218219It can be used like this:220221.. click:example::222223 @click.group(cls=AliasedGroup)224 def cli():225 pass226227 @cli.command228 def push():229 pass230231 @cli.command232 def pop():233 pass234235See the `alias example`_ in Click's repository for another example.236237.. _alias example: https://github.com/pallets/click/tree/main/examples/aliases238239111Parameter Modifications112-----------------------113114Parameters (options and arguments) are forwarded to the command callbacks
115 unmodified lines
230231 invoke(cli, prog_name='cli', args=['dist'])232233363.. _callback-evaluation-order:234365Callback Evaluation Order366-------------------------367368Click works a bit differently than some other command line parsers in that369it attempts to reconcile the order of arguments as defined by the370programmer with the order of arguments as defined by the user before371invoking any callbacks.372373This is an important concept to understand when porting complex374patterns to Click from optparse or other systems. A parameter375callback invocation in optparse happens as part of the parsing step,376whereas a callback invocation in Click happens after the parsing.377378The main difference is that in optparse, callbacks are invoked with the raw379value as it happens, whereas a callback in Click is invoked after the380value has been fully converted.381382Generally, the order of invocation is driven by the order in which the user383provides the arguments to the script; if there is an option called ``--foo``384and an option called ``--bar`` and the user calls it as ``--bar385--foo``, then the callback for ``bar`` will fire before the one for ``foo``.386387There are three exceptions to this rule which are important to know:388389Eagerness:390 An option can be set to be "eager". All eager parameters are391 evaluated before all non-eager parameters, but again in the order as392 they were provided on the command line by the user.393394 This is important for parameters that execute and exit like ``--help``395 and ``--version``. Both are eager parameters, but whatever parameter396 comes first on the command line will win and exit the program.397398Repeated parameters:399 If an option or argument is split up on the command line into multiple400 places because it is repeated -- for instance, ``--exclude foo --include401 baz --exclude bar`` -- the callback will fire based on the position of402 the first option. In this case, the callback will fire for403 ``exclude`` and it will be passed both options (``foo`` and404 ``bar``), then the callback for ``include`` will fire with ``baz``405 only.406407 Note that even if a parameter does not allow multiple versions, Click408 will still accept the position of the first, but it will ignore every409 value except the last. The reason for this is to allow composability410 through shell aliases that set defaults.411412Missing parameters:413 If a parameter is not defined on the command line, the callback will414 still fire. This is different from how it works in optparse where415 undefined values do not fire the callback. Missing parameters fire416 their callbacks at the very end which makes it possible for them to417 default to values from a parameter that came before.418419Most of the time you do not need to be concerned about any of this,420but it is important to know how it works for some advanced cases.421235.. _forwarding-unknown-options:236237Forwarding Unknown Options238--------------------------
88 unmodified lines
327everything below a subcommand be forwarded to another application than to328handle some arguments yourself.329330518Global Context Access519---------------------520521.. versionadded:: 5.0522523Starting with Click 5.0 it is possible to access the current context from524anywhere within the same thread through the use of the525:func:`get_current_context` function which returns it. This is primarily526useful for accessing the context bound object as well as some flags that527are stored on it to customize the runtime behavior. For instance the528:func:`echo` function does this to infer the default value of the `color`529flag.530531Example usage::532533 def get_current_command_name():534 return click.get_current_context().info_name535536It should be noted that this only works within the current thread. If you537spawn additional threads then those threads will not have the ability to538refer to the current context. If you want to give another thread the539ability to refer to this context you need to use the context within the540thread as a context manager::541542 def spawn_thread(ctx, func):543 def wrapper():544 with ctx:545 func()546 t = threading.Thread(target=wrapper)547 t.start()548 return t549550Now the thread function can access the context like the main thread would551do. However if you do use this for threading you need to be very careful552as the vast majority of the context is not thread safe! You are only553allowed to read from the context, but not to perform any modifications on554it.555556557Detecting the Source of a Parameter558-----------------------------------559560In some situations it's helpful to understand whether or not an option561or parameter came from the command line, the environment, the default562value, or :attr:`Context.default_map`. The563:meth:`Context.get_parameter_source` method can be used to find this564out. It will return a member of the :class:`~click.core.ParameterSource`565enum.566567.. click:example::568569 @click.command()570 @click.argument('port', nargs=1, default=8080, envvar="PORT")571 @click.pass_context572 def cli(ctx, port):573 source = ctx.get_parameter_source("port")574 click.echo(f"Port came from {source.name}")575576.. click:run::577578 invoke(cli, prog_name='cli', args=['8080'])579 println()580 invoke(cli, prog_name='cli', args=[], env={"PORT": "8080"})581 println()582 invoke(cli, prog_name='cli', args=[])583 println()584585331Managing Resources332------------------333334It can be useful to open a resource in a group, to be made available to
74 unmodified lines
added:docs/click-concepts.rst+67 added
1Click Concepts2================34This section covers concepts about Click's design.56.. contents::7 :depth: 18 :local:910.. _callback-evaluation-order:1112Callback Evaluation Order13-------------------------1415Click works a bit differently than some other command line parsers in that16it attempts to reconcile the order of arguments as defined by the17programmer with the order of arguments as defined by the user before18invoking any callbacks.1920This is an important concept to understand when porting complex21patterns to Click from optparse or other systems. A parameter22callback invocation in optparse happens as part of the parsing step,23whereas a callback invocation in Click happens after the parsing.2425The main difference is that in optparse, callbacks are invoked with the raw26value as it happens, whereas a callback in Click is invoked after the27value has been fully converted.2829Generally, the order of invocation is driven by the order in which the user30provides the arguments to the script; if there is an option called ``--foo``31and an option called ``--bar`` and the user calls it as ``--bar32--foo``, then the callback for ``bar`` will fire before the one for ``foo``.3334There are three exceptions to this rule which are important to know:3536Eagerness:37 An option can be set to be "eager". All eager parameters are38 evaluated before all non-eager parameters, but again in the order as39 they were provided on the command line by the user.4041 This is important for parameters that execute and exit like ``--help``42 and ``--version``. Both are eager parameters, but whatever parameter43 comes first on the command line will win and exit the program.4445Repeated parameters:46 If an option or argument is split up on the command line into multiple47 places because it is repeated -- for instance, ``--exclude foo --include48 baz --exclude bar`` -- the callback will fire based on the position of49 the first option. In this case, the callback will fire for50 ``exclude`` and it will be passed both options (``foo`` and51 ``bar``), then the callback for ``include`` will fire with ``baz``52 only.5354 Note that even if a parameter does not allow multiple versions, Click55 will still accept the position of the first, but it will ignore every56 value except the last. The reason for this is to allow composability57 through shell aliases that set defaults.5859Missing parameters:60 If a parameter is not defined on the command line, the callback will61 still fire. This is different from how it works in optparse where62 undefined values do not fire the callback. Missing parameters fire63 their callbacks at the very end which makes it possible for them to64 default to values from a parameter that came before.6566Most of the time you do not need to be concerned about any of this,67but it is important to know how it works for some advanced cases.
modified:docs/commands-and-groups.rst+84 added-11 removed
4 unmodified lines
56Commands 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: 19 :depth: 210 :local:1112Commands13--------------------1415Basic Command Example13----------------------16^^^^^^^^^^^^^^^^^^^^^^^17A simple command decorator takes no arguments.1819.. click:example::20 @click.command()
5 unmodified lines
26.. click:run::27 invoke(hello, args=['--count', '2',])2829Renaming Commands27------------------30^^^^^^^^^^^^^^^^^^^31By default the command is the function name with underscores replaced by dashes. To change this pass the desired name into the first positional argument.3233.. click:example::34 @click.command('say-hello')
5 unmodified lines
40.. click:run::41 invoke(hello, args=['--count', '2',])4243Deprecating Commands41---------------------44^^^^^^^^^^^^^^^^^^^^^^45To mark a command as deprecated pass in ``deprecated=True``4647.. click:example::48 @click.command('say-hello', deprecated=True)
4 unmodified lines
5354.. click:run::55 invoke(hello, args=['--count', '2',])5657Groups58------------5960Basic Group Example55---------------------61^^^^^^^^^^^^^^^^^^^^^62A group wraps one or more commands. 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.6364.. click:example::65 @click.group()
21 unmodified lines
8788As 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).8990Renaming Groups85-----------------91^^^^^^^^^^^^^^^^^92To have a name other than the decorated function name as the group name, pass it in as the first positional argument.9394.. click:example::95 @click.group('greet-someone')
10 unmodified lines
106107 invoke(greeting, args=['say-hello'])108109Group Invocation Without Command104--------------------------------110^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^111112By default, if a group is passed without a command, the group is not invoked and a command automatically passes ``--help``. To change this, pass ``invoke_without_command=True`` to the group. The context object also includes information about whether or not the group invocation would go to a command nested under it.113114.. click:example::
17 unmodified lines
132133134135Group Separation130--------------------------136^^^^^^^^^^^^^^^^^^^137Command :ref:`parameters` attached to a command belong only to that command.138139.. click:example::140 @click.group()
26 unmodified lines
167- ``tool sub --help`` returns the help for the ``sub`` subcommand.168- But ``tool --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.169170Arbitrary Nesting165------------------171^^^^^^^^^^^^^^^^^^^172:class:`Commands <Command>` are attached to a :class:`Group`. Multiple groups can be attached to another group. Groups containing multiple groups can be attached to a group, and so on. To invoke a command nested under multiple groups, all the groups under which it is nested must be invoked.173174.. click:example::175
18 unmodified lines
194195 invoke(cli, args=['session', 'initdb'])196197Lazily Attaching Commands192--------------------------198^^^^^^^^^^^^^^^^^^^^^^^^^^^199Most examples so far have attached the commands to a group immediately, but commands may be registered later. This could be used to split commands into multiple Python modules. Regardless of how they are attached, the commands are invoked identically.200201.. click:example::202
20 unmodified lines
223-------------------224The :class:`Context` object is how commands and groups communicate.225226Auto Envvar Prefix221--------------------227^^^^^^^^^^^^^^^^^^^^228Automatically built environment variables are supported for options only. To enable this feature, the ``auto_envvar_prefix`` parameter needs to be passed to the script that is invoked. Each command and parameter is then added as an uppercase underscore-separated variable. If you have a subcommand229called ``run`` taking an option called ``reload`` and the prefix is ``WEB``, then the variable is ``WEB_RUN_RELOAD``.230231Example usage:
40 unmodified lines
272273 invoke(cli, args=['greet',],274 env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},275 auto_envvar_prefix='GREETER')276277Global Context Access278---------------------279280.. versionadded:: 5.0281282Starting with Click 5.0 it is possible to access the current context from283anywhere within the same thread through the use of the284:func:`get_current_context` function which returns it. This is primarily285useful for accessing the context bound object as well as some flags that286are stored on it to customize the runtime behavior. For instance the287:func:`echo` function does this to infer the default value of the `color`288flag.289290Example usage::291292 def get_current_command_name():293 return click.get_current_context().info_name294295It should be noted that this only works within the current thread. If you296spawn additional threads then those threads will not have the ability to297refer to the current context. If you want to give another thread the298ability to refer to this context you need to use the context within the299thread as a context manager::300301 def spawn_thread(ctx, func):302 def wrapper():303 with ctx:304 func()305 t = threading.Thread(target=wrapper)306 t.start()307 return t308309Now the thread function can access the context like the main thread would310do. However if you do use this for threading you need to be very careful311as the vast majority of the context is not thread safe! You are only312allowed to read from the context, but not to perform any modifications on313it.314315316Detecting the Source of a Parameter317-----------------------------------318319In some situations it's helpful to understand whether or not an option320or parameter came from the command line, the environment, the default321value, or :attr:`Context.default_map`. The322:meth:`Context.get_parameter_source` method can be used to find this323out. It will return a member of the :class:`~click.core.ParameterSource`324enum.325326.. click:example::327328 @click.command()329 @click.argument('port', nargs=1, default=8080, envvar="PORT")330 @click.pass_context331 def cli(ctx, port):332 source = ctx.get_parameter_source("port")333 click.echo(f"Port came from {source.name}")334335.. click:run::336337 invoke(cli, prog_name='cli', args=['8080'])338 println()339 invoke(cli, prog_name='cli', args=[], env={"PORT": "8080"})340 println()341 invoke(cli, prog_name='cli', args=[])342 println()
modified:docs/complex.rst+4 added
14 unmodified lines
15In a theoretical world of two separate Click command line utilities, they16could solve this problem by nesting one inside the other. For instance, the17web framework could also load the commands for the message queue framework.1819.. contents::20 :depth: 121 :local:2223Basic Concepts24--------------2526To understand how this works, you need to understand two concepts: contexts
367 unmodified lines
added:docs/extending-click.rst+138 added
1Extending Click2=================34.. currentmodule:: click56In 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: 212 :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---------------7879Many tools support aliases for commands. For example, you can configure80``git`` to accept ``git ci`` as alias for ``git commit``. Other tools also81support auto-discovery for aliases by automatically shortening them.8283It's possible to customize :class:`Group` to provide this functionality. As84explained in :ref:`custom-groups`, a group provides two methods:85:meth:`~Group.list_commands` and :meth:`~Group.get_command`. In this particular86case, you only need to override the latter as you generally don't want to87enumerate the aliases on the help page in order to avoid confusion.8889The following example implements a subclass of :class:`Group` that accepts a90prefix for a command. If there was a command called ``push``, it would accept91``pus`` as an alias (so long as it was unique):9293.. click:example::9495 class AliasedGroup(click.Group):96 def get_command(self, ctx, cmd_name):97 rv = super().get_command(ctx, cmd_name)9899 if rv is not None:100 return rv101102 matches = [103 x for x in self.list_commands(ctx)104 if x.startswith(cmd_name)105 ]106107 if not matches:108 return None109110 if len(matches) == 1:111 return click.Group.get_command(self, ctx, matches[0])112113 ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")114115 def resolve_command(self, ctx, args):116 # always return the full command name117 _, cmd, args = super().resolve_command(ctx, args)118 return cmd.name, cmd, args119120It can be used like this:121122.. click:example::123124 @click.group(cls=AliasedGroup)125 def cli():126 pass127128 @cli.command129 def push():130 pass131132 @cli.command133 def pop():134 pass135136See the `alias example`_ in Click's repository for another example.137138.. _alias example: https://github.com/pallets/click/tree/main/examples/aliases
modified:docs/index.rst+3 added-1 removed
80 unmodified lines
81.. toctree::82 :maxdepth: 18384 why85 click-concepts8687General Reference88^^^^^^^^^^^^^^^^^^^89
9 unmodified lines
99 commands100 documentation101 prompts102 handling-files102 complex103 advanced104 complex105 extending-click106 testing107 utils108 shell-completion109 exceptions
28 unmodified lines