0
# Commands and Groups
1
2
Core decorators and classes for defining CLI commands and organizing them into hierarchical groups. Commands are the fundamental building blocks of CLI applications, while groups enable complex command structures with subcommands.
3
4
## Capabilities
5
6
### Command Creation
7
8
Creates individual CLI commands that can be executed directly. Commands wrap functions and provide CLI interface with automatic help generation, parameter parsing, and error handling.
9
10
```python { .api }
11
def command(
12
name: str | None = None,
13
cls: Type[Command] | None = None,
14
context_settings: dict[Any, Any] | None = None,
15
help: str | None = None,
16
epilog: str | None = None,
17
short_help: str | None = None,
18
options_metavar: str = "[OPTIONS]",
19
add_help_option: bool = True,
20
no_args_is_help: bool = False,
21
hidden: bool = False,
22
deprecated: bool = False,
23
) -> Callable[[Callable[..., Any]], Command]:
24
"""
25
Decorator that converts a function into a CLI command.
26
27
Parameters:
28
- name: Command name (defaults to function name)
29
- cls: Command class to use
30
- context_settings: Context configuration
31
- help: Command help text
32
- epilog: Text after help
33
- short_help: Brief help text
34
- options_metavar: Options display format
35
- add_help_option: Whether to add --help option
36
- no_args_is_help: Show help when no arguments provided
37
- hidden: Hide from help listing
38
- deprecated: Mark as deprecated
39
40
Returns:
41
Command decorator function
42
"""
43
```
44
45
**Usage Example:**
46
47
```python
48
@click.command()
49
@click.option('--verbose', is_flag=True, help='Enable verbose output')
50
def deploy(verbose):
51
"""Deploy the application."""
52
if verbose:
53
click.echo('Deploying with verbose output...')
54
else:
55
click.echo('Deploying...')
56
```
57
58
### Group Creation
59
60
Creates command groups that can contain multiple subcommands. Groups enable building hierarchical CLI applications with organized command structures.
61
62
```python { .api }
63
def group(
64
name: str | None = None,
65
cls: Type[Command] = Group,
66
commands: dict[str, Command] | None = None,
67
invoke_without_command: bool = False,
68
no_args_is_help: bool | None = None,
69
subcommand_metavar: str | None = None,
70
chain: bool = False,
71
result_callback: Callable[..., Any] | None = None,
72
help: str | None = None,
73
epilog: str | None = None,
74
short_help: str | None = None,
75
options_metavar: str = "[OPTIONS]",
76
add_help_option: bool = True,
77
hidden: bool = False,
78
deprecated: bool = False,
79
**kwargs: Any,
80
) -> Callable[[Callable[..., Any]], Group]:
81
"""
82
Decorator that converts a function into a CLI command group.
83
84
Parameters:
85
- name: Group name (defaults to function name)
86
- cls: Group class to use
87
- commands: Initial commands dictionary
88
- invoke_without_command: Allow group execution without subcommand
89
- no_args_is_help: Show help when no arguments provided
90
- subcommand_metavar: Subcommand display format
91
- chain: Enable command chaining
92
- result_callback: Callback for chained results
93
- help: Group help text
94
- epilog: Text after help
95
- short_help: Brief help text
96
- options_metavar: Options display format
97
- add_help_option: Whether to add --help option
98
- hidden: Hide from help listing
99
- deprecated: Mark as deprecated
100
101
Returns:
102
Group decorator function
103
"""
104
```
105
106
**Usage Example:**
107
108
```python
109
@click.group()
110
def database():
111
"""Database management commands."""
112
pass
113
114
@database.command()
115
def migrate():
116
"""Run database migrations."""
117
click.echo('Running migrations...')
118
119
@database.command()
120
@click.option('--force', is_flag=True, help='Force reset')
121
def reset(force):
122
"""Reset database."""
123
if force:
124
click.echo('Force resetting database...')
125
else:
126
click.echo('Resetting database...')
127
```
128
129
### Command Class
130
131
Direct Command class for programmatic command creation without decorators.
132
133
```python { .api }
134
class Command(BaseCommand):
135
callback: Callable[..., Any] | None
136
params: list[Parameter]
137
help: str | None
138
epilog: str | None
139
short_help: str | None
140
options_metavar: str
141
add_help_option: bool
142
no_args_is_help: bool
143
hidden: bool
144
deprecated: bool
145
146
def __init__(
147
self,
148
name: str,
149
context_settings: dict[Any, Any] | None = None,
150
callback: Callable[..., Any] | None = None,
151
params: list[Parameter] | None = None,
152
help: str | None = None,
153
epilog: str | None = None,
154
short_help: str | None = None,
155
options_metavar: str = "[OPTIONS]",
156
add_help_option: bool = True,
157
no_args_is_help: bool = False,
158
hidden: bool = False,
159
deprecated: bool = False,
160
) -> None:
161
"""
162
Command class for direct instantiation.
163
164
Parameters:
165
- name: Command name
166
- context_settings: Context configuration
167
- callback: Function to execute
168
- params: List of parameters
169
- help: Command help text
170
- epilog: Text after help
171
- short_help: Brief help text
172
- options_metavar: Options display format
173
- add_help_option: Whether to add --help option
174
- no_args_is_help: Show help when no arguments provided
175
- hidden: Hide from help listing
176
- deprecated: Mark as deprecated
177
"""
178
179
def get_params(self, ctx: Context) -> list[Parameter]: ...
180
def make_parser(self, ctx: Context) -> OptionParser: ...
181
def invoke(self, ctx: Context) -> Any: ...
182
```
183
184
### Group Class
185
186
Direct Group class for programmatic group creation with command management methods.
187
188
```python { .api }
189
class Group(MultiCommand):
190
commands: dict[str, Command]
191
192
def __init__(
193
self,
194
name: str | None = None,
195
commands: dict[str, Command] | None = None,
196
**attrs: Any
197
) -> None:
198
"""
199
Group class for direct instantiation.
200
201
Parameters:
202
- name: Group name
203
- commands: Initial commands dictionary
204
- **attrs: Additional attributes
205
"""
206
207
def add_command(self, cmd: Command, name: str | None = None) -> None:
208
"""
209
Add a command to the group.
210
211
Parameters:
212
- cmd: Command to add
213
- name: Command name (defaults to cmd.name)
214
"""
215
216
def command(self, *args: Any, **kwargs: Any) -> Callable[[Callable[..., Any]], Command]:
217
"""
218
Decorator to add a command to this group.
219
220
Returns:
221
Command decorator function
222
"""
223
224
def group(self, *args: Any, **kwargs: Any) -> Callable[[Callable[..., Any]], Group]:
225
"""
226
Decorator to add a subgroup to this group.
227
228
Returns:
229
Group decorator function
230
"""
231
232
def get_command(self, ctx: Context, cmd_name: str) -> Command | None: ...
233
def list_commands(self, ctx: Context) -> Iterable[str]: ...
234
```
235
236
### Base Command Classes
237
238
Foundation classes providing common functionality for all command types.
239
240
```python { .api }
241
class BaseCommand:
242
allow_extra_args: bool
243
allow_interspersed_args: bool
244
ignore_unknown_options: bool
245
name: str
246
context_settings: dict[Any, Any]
247
248
def __init__(self, name: str, context_settings: dict[Any, Any] | None = None) -> None: ...
249
def main(self, args: list[str] | None = None, **extra: Any) -> Any: ...
250
def __call__(self, *args: Any, **kwargs: Any) -> Any: ...
251
252
class MultiCommand(Command):
253
no_args_is_help: bool
254
invoke_without_command: bool
255
subcommand_metavar: str
256
chain: bool
257
result_callback: Callable[..., Any]
258
259
def resolve_command(self, ctx: Context, args: list[str]) -> tuple[str, Command, list[str]]: ...
260
def get_command(self, ctx: Context, cmd_name: str) -> Command | None: ...
261
def list_commands(self, ctx: Context) -> Iterable[str]: ...
262
```
263
264
### Command Collection
265
266
Utility for combining multiple command sources into a single interface.
267
268
```python { .api }
269
class CommandCollection(MultiCommand):
270
sources: list[MultiCommand]
271
272
def __init__(
273
self,
274
name: str | None = None,
275
sources: list[MultiCommand] | None = None,
276
**attrs: Any
277
) -> None:
278
"""
279
Collection of multiple command sources.
280
281
Parameters:
282
- name: Collection name
283
- sources: List of command sources
284
- **attrs: Additional attributes
285
"""
286
287
def add_source(self, multi_cmd: MultiCommand) -> None:
288
"""
289
Add a command source to the collection.
290
291
Parameters:
292
- multi_cmd: MultiCommand to add as source
293
"""
294
```