Skip to content
Myr

Move Commands-and-Groups doc from reST to MyST (#3259)

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

authored by Rowlando13 · committed by GitHub · parents a7d2a8d, a1a5e8e · Browse files · 2 files+372 added−342 removed
This commit

State

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

Diff stats

2 files+372 added−342 removed

  • other:+372 added−342 removed

2 files+372 added−342 removed

added:docs/commands-and-groups.md+372 added
1# Basic Commands, Groups, Context23```{currentmodule} click4```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---10depth: 211local: true12---13```1415## Commands1617### Basic Command Example1819A simple command decorator takes no arguments.2021```{eval-rst}22.. click:example::2324 @click.command()25 @click.option('--count', default=1)26 def hello(count):27 for x in range(count):28 click.echo("Hello!")2930.. click:run::31 invoke(hello, args=['--count', '2',])32```3334### Renaming Commands3536By default the command is the function name with underscores replaced by dashes. To change this pass the desired name into the first positional argument.3738```{eval-rst}39.. click:example::4041 @click.command('say-hello')42 @click.option('--count', default=1)43 def hello(count):44 for x in range(count):45 click.echo("Hello!")4647.. click:run::48 invoke(hello, args=['--count', '2',])49```5051### Deprecating Commands5253To mark a command as deprecated pass in `deprecated=True`5455```{eval-rst}56.. click:example::5758 @click.command('say-hello', deprecated=True)59 @click.option('--count', default=1)60 def hello(count):61 for x in range(count):62 click.echo("Hello!")6364.. click:run::65 invoke(hello, args=['--count', '2',])66```6768## Groups6970### Basic Group Example7172A 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.7374```{eval-rst}75.. click:example::7677 @click.group()78 def greeting():79 click.echo('Starting greeting ...')8081 @greeting.command('say-hello')82 @click.option('--count', default=1)83 def hello(count):84 for x in range(count):85 click.echo("Hello!")8687At the top level:8889.. click:run::9091 invoke(greeting)9293At the command level:9495.. click:run::9697 invoke(greeting, args=['say-hello'])98 invoke(greeting, args=['say-hello', '--help'])99```100101As 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).102103### Renaming Groups104105To have a name other than the decorated function name as the group name, pass it in as the first positional argument.106107```{eval-rst}108.. click:example::109110 @click.group('greet-someone')111 def greeting():112 click.echo('Starting greeting ...')113114 @greeting.command('say-hello')115 @click.option('--count', default=1)116 def hello(count):117 for x in range(count):118 click.echo("Hello!")119120.. click:run::121122 invoke(greeting, args=['say-hello'])123```124125### Group Invocation Without Command126127By 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.128129```{eval-rst}130.. click:example::131132 @click.group(invoke_without_command=True)133 @click.pass_context134 def cli(ctx):135 if ctx.invoked_subcommand is None:136 click.echo('I was invoked without subcommand')137 else:138 click.echo(f"I am about to invoke {ctx.invoked_subcommand}")139140 @cli.command()141 def sync():142 click.echo('The subcommand')143144.. click:run::145146 invoke(cli, prog_name='tool', args=[])147 invoke(cli, prog_name='tool', args=['sync'])148```149150### Group Separation151152Command {ref}`parameters` attached to a command belong only to that command.153154```{eval-rst}155.. click:example::156157 @click.group()158 def greeting():159 pass160161 @greeting.command()162 @click.option('--count', default=1)163 def hello(count):164 for x in range(count):165 click.echo("Hello!")166167 @greeting.command()168 @click.option('--count', default=1)169 def goodbye(count):170 for x in range(count):171 click.echo("Goodbye!")172173.. click:run::174175 invoke(greeting, args=['hello', '--count', '2'])176 invoke(greeting, args=['goodbye', '--count', '2'])177 invoke(greeting)178```179180Additionally 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.181182This behavior is observable with the `--help` option. Suppose we have a group called `tool` containing a command called `sub`.183184- `tool --help` returns the help for the whole program (listing subcommands).185- `tool sub --help` returns the help for the `sub` subcommand.186- 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.187188### Arbitrary Nesting189190{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.191192```{eval-rst}193.. click:example::194195 @click.group()196 def cli():197 pass198199 # Not @click so that the group is registered now.200 @cli.group()201 def session():202 click.echo('Starting session')203204 @session.command()205 def initdb():206 click.echo('Initialized the database')207208 @session.command()209 def dropdb():210 click.echo('Dropped the database')211212.. click:run::213214 invoke(cli, args=['session', 'initdb'])215```216217### Lazily Attaching Commands218219Most 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.220221```{eval-rst}222.. click:example::223224 @click.group()225 def cli():226 pass227228 @cli.command()229 def initdb():230 click.echo('Initialized the database')231232 @click.command()233 def dropdb():234 click.echo('Dropped the database')235236 cli.add_command(dropdb)237238.. click:run::239240 invoke(cli, args=['initdb'])241 invoke(cli, args=['dropdb'])242```243244## Context Object245The {class}`Context` object is how commands and groups communicate.246247### Auto Envvar Prefix248249Automatically 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 subcommand250called `run` taking an option called `reload` and the prefix is `WEB`, then the variable is `WEB_RUN_RELOAD`.251252Example usage:253254```{eval-rst}255.. click:example::256257 @click.command()258 @click.option('--username')259 def greet(username):260 click.echo(f'Hello {username}!')261262 if __name__ == '__main__':263 greet(auto_envvar_prefix='GREETER')264265And from the command line:266267.. click:run::268269 invoke(greet, env={'GREETER_USERNAME': 'john'},270 auto_envvar_prefix='GREETER')271```272273When using `auto_envvar_prefix` with command groups, the command name274needs to be included in the environment variable, between the prefix and275the parameter name, *i.e.* `PREFIX_COMMAND_VARIABLE`. If you have a276subcommand called `run-server` taking an option called `host` and277the prefix is `WEB`, then the variable is `WEB_RUN_SERVER_HOST`.278279```{eval-rst}280.. click:example::281282 @click.group()283 @click.option('--debug/--no-debug')284 def cli(debug):285 click.echo(f"Debug mode is {'on' if debug else 'off'}")286287 @cli.command()288 @click.option('--username')289 def greet(username):290 click.echo(f"Hello {username}!")291292 if __name__ == '__main__':293 cli(auto_envvar_prefix='GREETER')294295.. click:run::296297 invoke(cli, args=['greet',],298 env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'},299 auto_envvar_prefix='GREETER')300```301302### Global Context Access303304```{versionadded} 5.0305```306307Starting with Click 5.0 it is possible to access the current context from308anywhere within the same thread through the use of the309{func}`get_current_context` function which returns it. This is primarily310useful for accessing the context bound object as well as some flags that311are stored on it to customize the runtime behavior. For instance the312{func}`echo` function does this to infer the default value of the `color`313flag.314315Example usage:316317```python318 def get_current_command_name():319 return click.get_current_context().info_name320```321322It should be noted that this only works within the current thread. If you323spawn additional threads then those threads will not have the ability to324refer to the current context. If you want to give another thread the325ability to refer to this context you need to use the context within the326thread as a context manager:327328```python329 def spawn_thread(ctx, func):330 def wrapper():331 with ctx:332 func()333 t = threading.Thread(target=wrapper)334 t.start()335 return t336```337338Now the thread function can access the context like the main thread would339do. However if you do use this for threading you need to be very careful340as the vast majority of the context is not thread safe! You are only341allowed to read from the context, but not to perform any modifications on342it.343344345### Detecting the Source of a Parameter346347In some situations it's helpful to understand whether or not an option348or parameter came from the command line, the environment, the default349value, or {attr}`Context.default_map`. The350{meth}`Context.get_parameter_source` method can be used to find this351out. It will return a member of the {class}`~click.core.ParameterSource`352enum.353354```{eval-rst}355.. click:example::356357 @click.command()358 @click.argument('port', nargs=1, default=8080, envvar="PORT")359 @click.pass_context360 def cli(ctx, port):361 source = ctx.get_parameter_source("port")362 click.echo(f"Port came from {source.name}")363364.. click:run::365366 invoke(cli, prog_name='cli', args=['8080'])367 println()368 invoke(cli, prog_name='cli', args=[], env={"PORT": "8080"})369 println()370 invoke(cli, prog_name='cli', args=[])371 println()372```
deleted:docs/commands-and-groups.rst-342 removed
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: 210 :local:1112Commands13--------------------1415Basic Command Example16^^^^^^^^^^^^^^^^^^^^^^^17A simple command decorator takes no arguments.1819.. click:example::20 @click.command()21 @click.option('--count', default=1)22 def hello(count):23 for x in range(count):24 click.echo("Hello!")2526.. click:run::27 invoke(hello, args=['--count', '2',])2829Renaming Commands30^^^^^^^^^^^^^^^^^^^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')35 @click.option('--count', default=1)36 def hello(count):37 for x in range(count):38 click.echo("Hello!")3940.. click:run::41 invoke(hello, args=['--count', '2',])4243Deprecating Commands44^^^^^^^^^^^^^^^^^^^^^^45To mark a command as deprecated pass in ``deprecated=True``4647.. click:example::48 @click.command('say-hello', deprecated=True)49 @click.option('--count', default=1)50 def hello(count):51 for x in range(count):52 click.echo("Hello!")5354.. click:run::55 invoke(hello, args=['--count', '2',])5657Groups58------------5960Basic Group Example61^^^^^^^^^^^^^^^^^^^^^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()66 def greeting():67 click.echo('Starting greeting ...')6869 @greeting.command('say-hello')70 @click.option('--count', default=1)71 def hello(count):72 for x in range(count):73 click.echo("Hello!")7475At the top level:7677.. click:run::7879 invoke(greeting)8081At the command level:8283.. click:run::8485 invoke(greeting, args=['say-hello'])86 invoke(greeting, args=['say-hello', '--help'])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 Groups91^^^^^^^^^^^^^^^^^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')96 def greeting():97 click.echo('Starting greeting ...')9899 @greeting.command('say-hello')100 @click.option('--count', default=1)101 def hello(count):102 for x in range(count):103 click.echo("Hello!")104105.. click:run::106107 invoke(greeting, args=['say-hello'])108109Group Invocation Without Command110^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^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::115116 @click.group(invoke_without_command=True)117 @click.pass_context118 def cli(ctx):119 if ctx.invoked_subcommand is None:120 click.echo('I was invoked without subcommand')121 else:122 click.echo(f"I am about to invoke {ctx.invoked_subcommand}")123124 @cli.command()125 def sync():126 click.echo('The subcommand')127128.. click:run::129130 invoke(cli, prog_name='tool', args=[])131 invoke(cli, prog_name='tool', args=['sync'])132133134135Group Separation136^^^^^^^^^^^^^^^^^^^137Command :ref:`parameters` attached to a command belong only to that command.138139.. click:example::140 @click.group()141 def greeting():142 pass143144 @greeting.command()145 @click.option('--count', default=1)146 def hello(count):147 for x in range(count):148 click.echo("Hello!")149150 @greeting.command()151 @click.option('--count', default=1)152 def goodbye(count):153 for x in range(count):154 click.echo("Goodbye!")155156.. click:run::157158 invoke(greeting, args=['hello', '--count', '2'])159 invoke(greeting, args=['goodbye', '--count', '2'])160 invoke(greeting)161162Additionally 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.163164This behavior is observable with the ``--help`` option. Suppose we have a group called ``tool`` containing a command called ``sub``.165166- ``tool --help`` returns the help for the whole program (listing subcommands).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 Nesting171^^^^^^^^^^^^^^^^^^^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::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 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::202203 @click.group()204 def cli():205 pass206207 @cli.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(dropdb)216217.. click:run::218219 invoke(cli, args=['initdb'])220 invoke(cli, args=['dropdb'])221222Context Object223-------------------224The :class:`Context` object is how commands and groups communicate.225226Auto Envvar Prefix227^^^^^^^^^^^^^^^^^^^^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:232233.. click:example::234235 @click.command()236 @click.option('--username')237 def greet(username):238 click.echo(f'Hello {username}!')239240 if __name__ == '__main__':241 greet(auto_envvar_prefix='GREETER')242243And from the command line:244245.. click:run::246247 invoke(greet, env={'GREETER_USERNAME': 'john'},248 auto_envvar_prefix='GREETER')249250When using ``auto_envvar_prefix`` with command groups, the command name251needs to be included in the environment variable, between the prefix and252the parameter name, *i.e.* ``PREFIX_COMMAND_VARIABLE``. If you have a253subcommand called ``run-server`` taking an option called ``host`` and254the prefix is ``WEB``, then the variable is ``WEB_RUN_SERVER_HOST``.255256.. click:example::257258 @click.group()259 @click.option('--debug/--no-debug')260 def cli(debug):261 click.echo(f"Debug mode is {'on' if debug else 'off'}")262263 @cli.command()264 @click.option('--username')265 def greet(username):266 click.echo(f"Hello {username}!")267268 if __name__ == '__main__':269 cli(auto_envvar_prefix='GREETER')270271.. click:run::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()