| 1 |
# Basic Commands, Groups, Context |
| 2 |
|
| 3 |
```{currentmodule} click |
| 4 |
``` |
| 5 |
|
| 6 |
Commands and Groups are the building blocks for Click applications. |
| 7 |
{class}`Command` wraps a function to make it into a cli command. {class}`Group` |
| 8 |
wraps Commands and Groups to make them into applications. {class}`Context` is |
| 9 |
how groups and commands communicate. |
| 10 |
|
| 11 |
```{contents} |
| 12 |
--- |
| 13 |
depth: 2 |
| 14 |
local: true |
| 15 |
--- |
| 16 |
``` |
| 17 |
|
| 18 |
## Commands |
| 19 |
|
| 20 |
### Basic Command Example |
| 21 |
|
| 22 |
A simple command decorator takes no arguments. |
| 23 |
|
| 24 |
```{eval-rst} |
| 25 |
.. click:example:: |
| 26 |
|
| 27 |
@click.command() |
| 28 |
@click.option('--count', default=1) |
| 29 |
def hello(count): |
| 30 |
for x in range(count): |
| 31 |
click.echo("Hello!") |
| 32 |
|
| 33 |
.. click:run:: |
| 34 |
invoke(hello, args=['--count', '2',]) |
| 35 |
``` |
| 36 |
|
| 37 |
### Renaming Commands |
| 38 |
|
| 39 |
By default the command is the function name with underscores replaced by dashes. |
| 40 |
To change this pass the desired name into the first positional argument. |
| 41 |
|
| 42 |
```{eval-rst} |
| 43 |
.. click:example:: |
| 44 |
|
| 45 |
@click.command('say-hello') |
| 46 |
@click.option('--count', default=1) |
| 47 |
def hello(count): |
| 48 |
for x in range(count): |
| 49 |
click.echo("Hello!") |
| 50 |
|
| 51 |
.. click:run:: |
| 52 |
invoke(hello, args=['--count', '2',]) |
| 53 |
``` |
| 54 |
|
| 55 |
### Deprecating Commands |
| 56 |
|
| 57 |
To mark a command as deprecated pass in `deprecated=True` |
| 58 |
|
| 59 |
```{eval-rst} |
| 60 |
.. click:example:: |
| 61 |
|
| 62 |
@click.command('say-hello', deprecated=True) |
| 63 |
@click.option('--count', default=1) |
| 64 |
def hello(count): |
| 65 |
for x in range(count): |
| 66 |
click.echo("Hello!") |
| 67 |
|
| 68 |
.. click:run:: |
| 69 |
invoke(hello, args=['--count', '2',]) |
| 70 |
``` |
| 71 |
|
| 72 |
## Groups |
| 73 |
|
| 74 |
### Basic Group Example |
| 75 |
|
| 76 |
A group wraps one or more commands. After being wrapped, the commands are nested |
| 77 |
under that group. You can see that on the help pages and in the execution. By |
| 78 |
default, invoking the group with no command shows the help page. |
| 79 |
|
| 80 |
```{eval-rst} |
| 81 |
.. click:example:: |
| 82 |
|
| 83 |
@click.group() |
| 84 |
def greeting(): |
| 85 |
click.echo('Starting greeting ...') |
| 86 |
|
| 87 |
@greeting.command('say-hello') |
| 88 |
@click.option('--count', default=1) |
| 89 |
def hello(count): |
| 90 |
for x in range(count): |
| 91 |
click.echo("Hello!") |
| 92 |
|
| 93 |
At the top level: |
| 94 |
|
| 95 |
.. click:run:: |
| 96 |
|
| 97 |
invoke(greeting) |
| 98 |
|
| 99 |
At the command level: |
| 100 |
|
| 101 |
.. click:run:: |
| 102 |
|
| 103 |
invoke(greeting, args=['say-hello']) |
| 104 |
invoke(greeting, args=['say-hello', '--help']) |
| 105 |
``` |
| 106 |
|
| 107 |
As you can see from the above example, the function wrapped by the group |
| 108 |
decorator executes unless it is interrupted (for example by calling the help). |
| 109 |
|
| 110 |
### Renaming Groups |
| 111 |
|
| 112 |
To have a name other than the decorated function name as the group name, pass it |
| 113 |
in as the first positional argument. |
| 114 |
|
| 115 |
```{eval-rst} |
| 116 |
.. click:example:: |
| 117 |
|
| 118 |
@click.group('greet-someone') |
| 119 |
def greeting(): |
| 120 |
click.echo('Starting greeting ...') |
| 121 |
|
| 122 |
@greeting.command('say-hello') |
| 123 |
@click.option('--count', default=1) |
| 124 |
def hello(count): |
| 125 |
for x in range(count): |
| 126 |
click.echo("Hello!") |
| 127 |
|
| 128 |
.. click:run:: |
| 129 |
|
| 130 |
invoke(greeting, args=['say-hello']) |
| 131 |
``` |
| 132 |
|
| 133 |
### Group Invocation Without Command |
| 134 |
|
| 135 |
By default, if a group is passed without a command, the group is not invoked and |
| 136 |
a command automatically passes `--help`. To change this, pass |
| 137 |
`invoke_without_command=True` to the group. The context object also includes |
| 138 |
information about whether or not the group invocation would go to a command |
| 139 |
nested under it. |
| 140 |
|
| 141 |
```{eval-rst} |
| 142 |
.. click:example:: |
| 143 |
|
| 144 |
@click.group(invoke_without_command=True) |
| 145 |
@click.pass_context |
| 146 |
def cli(ctx): |
| 147 |
if ctx.invoked_subcommand is None: |
| 148 |
click.echo('I was invoked without subcommand') |
| 149 |
else: |
| 150 |
click.echo(f"I am about to invoke {ctx.invoked_subcommand}") |
| 151 |
|
| 152 |
@cli.command() |
| 153 |
def sync(): |
| 154 |
click.echo('The subcommand') |
| 155 |
|
| 156 |
.. click:run:: |
| 157 |
|
| 158 |
invoke(cli, prog_name='tool', args=[]) |
| 159 |
invoke(cli, prog_name='tool', args=['sync']) |
| 160 |
``` |
| 161 |
|
| 162 |
### Group Separation |
| 163 |
|
| 164 |
Command {ref}`parameters` attached to a command belong only to that command. |
| 165 |
|
| 166 |
```{eval-rst} |
| 167 |
.. click:example:: |
| 168 |
|
| 169 |
@click.group() |
| 170 |
def greeting(): |
| 171 |
pass |
| 172 |
|
| 173 |
@greeting.command() |
| 174 |
@click.option('--count', default=1) |
| 175 |
def hello(count): |
| 176 |
for x in range(count): |
| 177 |
click.echo("Hello!") |
| 178 |
|
| 179 |
@greeting.command() |
| 180 |
@click.option('--count', default=1) |
| 181 |
def goodbye(count): |
| 182 |
for x in range(count): |
| 183 |
click.echo("Goodbye!") |
| 184 |
|
| 185 |
.. click:run:: |
| 186 |
|
| 187 |
invoke(greeting, args=['hello', '--count', '2']) |
| 188 |
invoke(greeting, args=['goodbye', '--count', '2']) |
| 189 |
invoke(greeting) |
| 190 |
``` |
| 191 |
|
| 192 |
Additionally parameters for a given group belong only to that group and not to |
| 193 |
the commands under it. What this means is that options and arguments for a |
| 194 |
specific command have to be specified *after* the command name itself, but |
| 195 |
*before* any other command names. |
| 196 |
|
| 197 |
This behavior is observable with the `--help` option. Suppose we have a group |
| 198 |
called `tool` containing a command called `sub`. |
| 199 |
|
| 200 |
- `tool --help` returns the help for the whole program (listing subcommands). |
| 201 |
- `tool sub --help` returns the help for the `sub` subcommand. |
| 202 |
- But `tool --help sub` treats `--help` as an argument for the main program. |
| 203 |
Click then invokes the callback for `--help`, which prints the help and aborts |
| 204 |
the program before click can process the subcommand. |
| 205 |
|
| 206 |
### Arbitrary Nesting |
| 207 |
|
| 208 |
{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. |
| 209 |
|
| 210 |
```{eval-rst} |
| 211 |
.. click:example:: |
| 212 |
|
| 213 |
@click.group() |
| 214 |
def cli(): |
| 215 |
pass |
| 216 |
|
| 217 |
# Not @click so that the group is registered now. |
| 218 |
@cli.group() |
| 219 |
def session(): |
| 220 |
click.echo('Starting session') |
| 221 |
|
| 222 |
@session.command() |
| 223 |
def initdb(): |
| 224 |
click.echo('Initialized the database') |
| 225 |
|
| 226 |
@session.command() |
| 227 |
def dropdb(): |
| 228 |
click.echo('Dropped the database') |
| 229 |
|
| 230 |
.. click:run:: |
| 231 |
|
| 232 |
invoke(cli, args=['session', 'initdb']) |
| 233 |
``` |
| 234 |
|
| 235 |
### Lazily Attaching Commands |
| 236 |
|
| 237 |
Most examples so far have attached the commands to a group immediately, but |
| 238 |
commands may be registered later. This could be used to split commands into |
| 239 |
multiple Python modules. Regardless of how they are attached, the commands are |
| 240 |
invoked identically. |
| 241 |
|
| 242 |
```{eval-rst} |
| 243 |
.. click:example:: |
| 244 |
|
| 245 |
@click.group() |
| 246 |
def cli(): |
| 247 |
pass |
| 248 |
|
| 249 |
@cli.command() |
| 250 |
def initdb(): |
| 251 |
click.echo('Initialized the database') |
| 252 |
|
| 253 |
@click.command() |
| 254 |
def dropdb(): |
| 255 |
click.echo('Dropped the database') |
| 256 |
|
| 257 |
cli.add_command(dropdb) |
| 258 |
|
| 259 |
.. click:run:: |
| 260 |
|
| 261 |
invoke(cli, args=['initdb']) |
| 262 |
invoke(cli, args=['dropdb']) |
| 263 |
``` |
| 264 |
|
| 265 |
## Context Object |
| 266 |
The {class}`Context` object is how commands and groups communicate. |
| 267 |
|
| 268 |
### Auto Envvar Prefix |
| 269 |
|
| 270 |
Automatically built environment variables are supported for options only. To |
| 271 |
enable this feature, the `auto_envvar_prefix` parameter needs to be passed to |
| 272 |
the script that is invoked. Each command and parameter is then added as an |
| 273 |
uppercase underscore-separated variable. If you have a subcommand |
| 274 |
called `run` taking an option called `reload` and the prefix is `WEB`, then the |
| 275 |
variable is `WEB_RUN_RELOAD`. |
| 276 |
|
| 277 |
Example usage: |
| 278 |
|
| 279 |
```{eval-rst} |
| 280 |
.. click:example:: |
| 281 |
|
| 282 |
@click.command() |
| 283 |
@click.option('--username') |
| 284 |
def greet(username): |
| 285 |
click.echo(f'Hello {username}!') |
| 286 |
|
| 287 |
if __name__ == '__main__': |
| 288 |
greet(auto_envvar_prefix='GREETER') |
| 289 |
|
| 290 |
And from the command line: |
| 291 |
|
| 292 |
.. click:run:: |
| 293 |
|
| 294 |
invoke(greet, env={'GREETER_USERNAME': 'john'}, |
| 295 |
auto_envvar_prefix='GREETER') |
| 296 |
``` |
| 297 |
|
| 298 |
When using `auto_envvar_prefix` with command groups, the command name |
| 299 |
needs to be included in the environment variable, between the prefix and |
| 300 |
the parameter name, *i.e.* `PREFIX_COMMAND_VARIABLE`. If you have a |
| 301 |
subcommand called `run-server` taking an option called `host` and |
| 302 |
the prefix is `WEB`, then the variable is `WEB_RUN_SERVER_HOST`. |
| 303 |
|
| 304 |
```{eval-rst} |
| 305 |
.. click:example:: |
| 306 |
|
| 307 |
@click.group() |
| 308 |
@click.option('--debug/--no-debug') |
| 309 |
def cli(debug): |
| 310 |
click.echo(f"Debug mode is {'on' if debug else 'off'}") |
| 311 |
|
| 312 |
@cli.command() |
| 313 |
@click.option('--username') |
| 314 |
def greet(username): |
| 315 |
click.echo(f"Hello {username}!") |
| 316 |
|
| 317 |
if __name__ == '__main__': |
| 318 |
cli(auto_envvar_prefix='GREETER') |
| 319 |
|
| 320 |
.. click:run:: |
| 321 |
|
| 322 |
invoke(cli, args=['greet',], |
| 323 |
env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'}, |
| 324 |
auto_envvar_prefix='GREETER') |
| 325 |
``` |
| 326 |
|
| 327 |
### Global Context Access |
| 328 |
|
| 329 |
```{versionadded} 5.0 |
| 330 |
``` |
| 331 |
|
| 332 |
Starting with Click 5.0 it is possible to access the current context from |
| 333 |
anywhere within the same thread through the use of the |
| 334 |
{func}`get_current_context` function which returns it. This is primarily |
| 335 |
useful for accessing the context bound object as well as some flags that |
| 336 |
are stored on it to customize the runtime behavior. For instance the |
| 337 |
{func}`echo` function does this to infer the default value of the `color` |
| 338 |
flag. |
| 339 |
|
| 340 |
Example usage: |
| 341 |
|
| 342 |
```python |
| 343 |
def get_current_command_name(): |
| 344 |
return click.get_current_context().info_name |
| 345 |
``` |
| 346 |
|
| 347 |
It should be noted that this only works within the current thread. If you |
| 348 |
spawn additional threads then those threads will not have the ability to |
| 349 |
refer to the current context. If you want to give another thread the |
| 350 |
ability to refer to this context you need to use the context within the |
| 351 |
thread as a context manager: |
| 352 |
|
| 353 |
```python |
| 354 |
def spawn_thread(ctx, func): |
| 355 |
def wrapper(): |
| 356 |
with ctx: |
| 357 |
func() |
| 358 |
t = threading.Thread(target=wrapper) |
| 359 |
t.start() |
| 360 |
return t |
| 361 |
``` |
| 362 |
|
| 363 |
Now the thread function can access the context like the main thread would |
| 364 |
do. However if you do use this for threading you need to be very careful |
| 365 |
as the vast majority of the context is not thread safe! You are only |
| 366 |
allowed to read from the context, but not to perform any modifications on |
| 367 |
it. |
| 368 |
|
| 369 |
|
| 370 |
### Parameter Source Priority |
| 371 |
|
| 372 |
When a parameter's value is resolved, Click checks several sources |
| 373 |
in the following order of precedence: |
| 374 |
|
| 375 |
1. **Prompt** (`PROMPT`): interactively provided by the user at a prompt. |
| 376 |
2. **Command line** (`COMMANDLINE`): provided as a CLI argument or option. |
| 377 |
3. **Environment variable** (`ENVIRONMENT`): read from an environment variable. |
| 378 |
4. **Default map** (`DEFAULT_MAP`): looked up from {attr}`Context.default_map`. |
| 379 |
5. **Default** (`DEFAULT`): the default value defined on the parameter. |
| 380 |
|
| 381 |
{class}`~click.core.ParameterSource` members are ordered from most |
| 382 |
explicit to least explicit. Because it is an {class}`~enum.IntEnum`, |
| 383 |
you can use comparison operators to check how explicitly a value was |
| 384 |
provided: |
| 385 |
|
| 386 |
```python |
| 387 |
source = ctx.get_parameter_source("port") |
| 388 |
|
| 389 |
# True if the value was explicitly set (command line, prompt, or env var). |
| 390 |
if source < click.ParameterSource.DEFAULT_MAP: |
| 391 |
... |
| 392 |
|
| 393 |
# True if the value came from any kind of default. |
| 394 |
if source >= click.ParameterSource.DEFAULT_MAP: |
| 395 |
... |
| 396 |
``` |
| 397 |
|
| 398 |
|
| 399 |
### Detecting the Source of a Parameter |
| 400 |
|
| 401 |
In some situations it's helpful to understand whether or not an option |
| 402 |
or parameter came from the command line, the environment, the default |
| 403 |
value, or {attr}`Context.default_map`. The |
| 404 |
{meth}`Context.get_parameter_source` method can be used to find this |
| 405 |
out. It will return a member of the {class}`~click.core.ParameterSource` |
| 406 |
enum. |
| 407 |
|
| 408 |
```{eval-rst} |
| 409 |
.. click:example:: |
| 410 |
|
| 411 |
@click.command() |
| 412 |
@click.argument('port', nargs=1, default=8080, envvar="PORT") |
| 413 |
@click.pass_context |
| 414 |
def cli(ctx, port): |
| 415 |
source = ctx.get_parameter_source("port") |
| 416 |
click.echo(f"Port came from {source.name}") |
| 417 |
|
| 418 |
.. click:run:: |
| 419 |
|
| 420 |
invoke(cli, prog_name='cli', args=['8080']) |
| 421 |
println() |
| 422 |
invoke(cli, prog_name='cli', args=[], env={"PORT": "8080"}) |
| 423 |
println() |
| 424 |
invoke(cli, prog_name='cli', args=[]) |
| 425 |
println() |
| 426 |
``` |