Debian Codegraph @

docs/features/modular_commands.md

raw symbols SCIP
1 # Modular Commands
2
3 ## Overview
4
5 Cmd2 also enables developers to modularize their command definitions into
6 [CommandSet][cmd2.CommandSet] objects. CommandSets represent a logical grouping of commands within a
7 `cmd2` application. By default, `CommandSet` objects need to be manually registered. However, it is
8 possible for all `CommandSet` objects to be discovered and loaded automatically when the
9 [cmd2.Cmd][] class is instantiated with this mixin by setting `auto_load_commands=True`. This also
10 enables the developer to dynamically add/remove commands from the `cmd2` application. This could be
11 useful for loadable plugins that add additional capabilities. Additionally, it allows for
12 object-oriented encapsulation and garbage collection of state that is specific to a CommandSet.
13
14 ### Features
15
16 - Modular Command Sets - Commands can be broken into separate modules rather than in one god class
17 holding all commands.
18 - Automatic Command Discovery - In your application, merely defining and importing a CommandSet is
19 sufficient for `cmd2` to discover and load your command if you set `auto_load_commands=True`. No
20 manual registration is necessary.
21 - Dynamically Loadable/Unloadable Commands - Command functions and CommandSets can both be loaded
22 and unloaded dynamically during application execution. This can enable features such as
23 dynamically loaded modules that add additional commands.
24 - Events handlers - Four event handlers are provided in `CommandSet` class for custom initialization
25 and cleanup steps. See [Event Handlers](#event-handlers).
26 - Subcommand Injection - Subcommands can be defined separately from the base command. This allows
27 for a more action-centric instead of object-centric command system while still organizing your
28 code and handlers around the objects being managed.
29
30 See API documentation for [cmd2.CommandSet][].
31
32 See [the examples](https://github.com/python-cmd2/cmd2/tree/main/examples/modular_commands) for more
33 details.
34
35 ## Defining Commands
36
37 ### Command Sets
38
39 CommandSets group multiple commands together. The plugin will inspect functions within a
40 `CommandSet` using the same rules as when they're defined in `cmd2.Cmd`. Commands must be prefixed
41 with `do_`, help functions with `help_`, and completer functions with `complete_`.
42
43 CommandSet command methods will always expect the same parameters as when defined in a `cmd2.Cmd`
44 sub-class, except that `self` will now refer to the `CommandSet` instead of the cmd2 instance. The
45 cmd2 instance can be accessed through `self._cmd` that is populated when the `CommandSet` is
46 registered.
47
48 CommandSets will only be auto-loaded if the initializer takes no arguments. If you need to provide
49 initializer arguments, see [Manual CommandSet Construction](#manual-commandset-construction).
50
51 ```py
52 import cmd2
53 from cmd2 import CommandSet
54
55 class ExampleApp(cmd2.Cmd):
56 """
57 CommandSets are automatically loaded. Nothing needs to be done.
58 """
59 def __init__(self, *args, **kwargs):
60 super().__init__(*args, auto_load_commands=True, **kwargs)
61
62 def do_something(self, arg):
63 """Something Command."""
64 self.poutput('this is the something command')
65
66 class AutoLoadCommandSet(CommandSet[ExampleApp]):
67 DEFAULT_CATEGORY = 'My Category'
68
69 def __init__(self):
70 super().__init__()
71
72 def do_hello(self, _: cmd2.Statement):
73 """Hello Command."""
74 self._cmd.poutput('Hello')
75
76 def do_world(self, _: cmd2.Statement):
77 """World Command."""
78 self._cmd.poutput('World')
79 ```
80
81 ### Manual CommandSet Construction
82
83 If a CommandSet class requires parameters to be provided to the initializer, you may manually
84 construct CommandSets and pass in the initializer to Cmd2.
85
86 ```py
87 import cmd2
88 from cmd2 import CommandSet
89
90 class ExampleApp(cmd2.Cmd):
91 """
92 CommandSets with initializer parameters are provided in the initializer
93 """
94 def __init__(self, *args, **kwargs):
95 # gotta have this or neither the plugin or cmd2 will initialize
96 super().__init__(*args, auto_load_commands=True, **kwargs)
97
98 def do_something(self, arg):
99 """Something Command."""
100 self.last_result = 5
101 self.poutput('this is the something command')
102
103 class CustomInitCommandSet(CommandSet[ExampleApp]):
104 DEFAULT_CATEGORY = 'My Category'
105
106 def __init__(self, arg1, arg2):
107 super().__init__()
108
109 self._arg1 = arg1
110 self._arg2 = arg2
111
112 def do_show_arg1(self, _: cmd2.Statement):
113 """Show Arg 1."""
114 self._cmd.poutput(f'Arg1: {self._arg1}')
115
116 def do_show_arg2(self, _: cmd2.Statement):
117 """Show Arg 2."""
118 self._cmd.poutput(f'Arg2: {self._arg2}')
119
120
121 def main():
122 my_commands = CustomInitCommandSet(1, 2)
123 app = ExampleApp(command_sets=[my_commands])
124 app.cmdloop()
125 ```
126
127 ### Type Hinting and self.\_cmd
128
129 When a `CommandSet` is registered, its `_cmd` property is populated with a reference to the
130 `cmd2.Cmd` instance. `CommandSet` is a
131 [generic](https://docs.python.org/3/library/typing.html#typing.Generic) class, allowing you to
132 specify the specific `cmd2.Cmd` subclass it expects to be loaded into.
133
134 By parameterizing the inheritance with your application class, your IDE and static analysis tools
135 (like Mypy) will know the exact type of `self._cmd`. This provides full autocompletion and type
136 validation when accessing custom attributes or methods on your main application instance.
137
138 ```py
139 import cmd2
140 from cmd2 import CommandSet
141
142 class MyApp(cmd2.Cmd):
143 def __init__(self):
144 super().__init__()
145 self.custom_state = "Some important data"
146
147 class MyCommands(CommandSet[MyApp]):
148 def do_check_state(self, _: cmd2.Statement):
149 # Type checkers know self._cmd is an instance of MyApp
150 # and can validate the 'custom_state' attribute exists.
151 self._cmd.poutput(f"State: {self._cmd.custom_state}")
152 ```
153
154 ### Dynamic Commands
155
156 You can also dynamically load and unload commands by installing and removing CommandSets at runtime.
157 For example, you can support runtime loadable plugins or add/remove commands based on your state.
158
159 You may need to disable command auto-loading if you need to dynamically load commands at runtime.
160
161 ```py
162 import argparse
163 import cmd2
164 from cmd2 import CommandSet, with_argparser, with_category
165
166
167 class LoadableFruits(CommandSet["ExampleApp"]):
168 DEFAULT_CATEGORY = 'Fruits'
169
170 def __init__(self):
171 super().__init__()
172
173 def do_apple(self, _: cmd2.Statement):
174 """Apple Command."""
175 self._cmd.poutput('Apple')
176
177 def do_banana(self, _: cmd2.Statement):
178 """Banana Command."""
179 self._cmd.poutput('Banana')
180
181
182 class LoadableVegetables(CommandSet["ExampleApp"]):
183 DEFAULT_CATEGORY = 'Vegetables'
184
185 def __init__(self):
186 super().__init__()
187
188 def do_arugula(self, _: cmd2.Statement):
189 """Arugula Command."""
190 self._cmd.poutput('Arugula')
191
192 def do_bokchoy(self, _: cmd2.Statement):
193 """Bok Choy Command."""
194 self._cmd.poutput('Bok Choy')
195
196
197 class ExampleApp(cmd2.Cmd):
198 """
199 CommandSets are loaded via the `load` and `unload` commands
200 """
201
202 def __init__(self, *args, **kwargs):
203 # gotta have this or neither the plugin or cmd2 will initialize
204 super().__init__(*args, auto_load_commands=False, **kwargs)
205
206 self._fruits = LoadableFruits()
207 self._vegetables = LoadableVegetables()
208
209 load_parser = cmd2.Cmd2ArgumentParser()
210 load_parser.add_argument('cmds', choices=['fruits', 'vegetables'])
211
212 @with_argparser(load_parser)
213 @with_category('Command Loading')
214 def do_load(self, ns: argparse.Namespace):
215 """Load Command."""
216 if ns.cmds == 'fruits':
217 try:
218 self.register_command_set(self._fruits)
219 self.poutput('Fruits loaded')
220 except ValueError:
221 self.poutput('Fruits already loaded')
222
223 if ns.cmds == 'vegetables':
224 try:
225 self.register_command_set(self._vegetables)
226 self.poutput('Vegetables loaded')
227 except ValueError:
228 self.poutput('Vegetables already loaded')
229
230 @with_argparser(load_parser)
231 def do_unload(self, ns: argparse.Namespace):
232 """Unload Command."""
233 if ns.cmds == 'fruits':
234 self.unregister_command_set(self._fruits)
235 self.poutput('Fruits unloaded')
236
237 if ns.cmds == 'vegetables':
238 self.unregister_command_set(self._vegetables)
239 self.poutput('Vegetables unloaded')
240
241
242 if __name__ == '__main__':
243 app = ExampleApp()
244 app.cmdloop()
245 ```
246
247 ## Event Handlers
248
249 The following functions are called at different points in the [CommandSet][cmd2.CommandSet] life
250 cycle.
251
252 [on_register][cmd2.command_set.CommandSet.on_register] - Called by `cmd2.Cmd` as the first step to
253 registering a `CommandSet`. The commands defined in this class have not be added to the CLI object
254 at this point. Subclasses can override this to perform any initialization requiring access to the
255 Cmd object (e.g. configure commands and their parsers based on CLI state data).
256
257 [on_registered][cmd2.command_set.CommandSet.on_registered] - Called by `cmd2.Cmd` after a
258 `CommandSet` is registered and all its commands have been added to the CLI. Subclasses can override
259 this to perform custom steps related to the newly added commands (e.g. setting them to a disabled
260 state).
261
262 [on_unregister][cmd2.command_set.CommandSet.on_unregister] - Called by `cmd2.Cmd` as the first step
263 to unregistering a `CommandSet`. Subclasses can override this to perform any cleanup steps which
264 require their commands being registered in the CLI.
265
266 [on_unregistered][cmd2.command_set.CommandSet.on_unregistered] - Called by `cmd2.Cmd` after a
267 `CommandSet` has been unregistered and all its commands removed from the CLI. Subclasses can
268 override this to perform remaining cleanup steps.
269
270 ## Injecting Subcommands
271
272 ### Description
273
274 Using the [@with_argparser][cmd2.with_argparser] and [@as_subcommand_to][cmd2.as_subcommand_to]
275 decorators, it is possible to easily define subcommands for your command. This has a tendency to
276 drive your interface into an object-centric interface. For example, imagine you have a tool that
277 manages your media collection and you want to manage movies or shows. An object-centric approach
278 would push you to have base commands such as `movies` and `shows` which each have subcommands `add`,
279 `edit`, `list`, `delete`. If you wanted to present an action-centric command set, so that `add`,
280 `edit`, `list`, and `delete` are the base commands, you'd have to organize your code around these
281 similar actions rather than organizing your code around similar objects being managed.
282
283 Subcommand injection allows you to inject subcommands into a base command to present an interface
284 that is sensible to a user while still organizing your code in whatever structure makes more logical
285 sense to the developer.
286
287 ### Example
288
289 This example is a variation on the Dynamic Commands example above. A `cut` command is introduced as
290 a base command and each CommandSet adds a subcommand to it.
291
292 ```py
293 import argparse
294 import cmd2
295 from cmd2 import CommandSet, with_argparser, with_category
296
297
298 class LoadableFruits(CommandSet["ExampleApp"]):
299 DEFAULT_CATEGORY = 'Fruits'
300
301 def __init__(self):
302 super().__init__()
303
304 def do_apple(self, _: cmd2.Statement):
305 """Apple Command."""
306 self._cmd.poutput('Apple')
307
308 banana_parser = cmd2.Cmd2ArgumentParser()
309 banana_parser.add_argument('direction', choices=['discs', 'lengthwise'])
310
311 @cmd2.as_subcommand_to('cut', 'banana', banana_parser)
312 def cut_banana(self, ns: argparse.Namespace):
313 """Cut banana"""
314 self._cmd.poutput('cutting banana: ' + ns.direction)
315
316
317 class LoadableVegetables(CommandSet["ExampleApp"]):
318 DEFAULT_CATEGORY = 'Vegetables'
319
320 def __init__(self):
321 super().__init__()
322
323 def do_arugula(self, _: cmd2.Statement):
324 """Arugula Command."""
325 self._cmd.poutput('Arugula')
326
327 bokchoy_parser = cmd2.Cmd2ArgumentParser()
328 bokchoy_parser.add_argument('style', choices=['quartered', 'diced'])
329
330 @cmd2.as_subcommand_to('cut', 'bokchoy', bokchoy_parser)
331 def cut_bokchoy(self, _: argparse.Namespace):
332 """Cut bok choy."""
333 self._cmd.poutput('Bok Choy')
334
335
336 class ExampleApp(cmd2.Cmd):
337 """
338 CommandSets are loaded dynamically at runtime via other commands.
339 """
340
341 def __init__(self, *args, **kwargs):
342 # gotta have this or neither the plugin or cmd2 will initialize
343 super().__init__(*args, auto_load_commands=False, **kwargs)
344
345 self._fruits = LoadableFruits()
346 self._vegetables = LoadableVegetables()
347
348 load_parser = cmd2.Cmd2ArgumentParser()
349 load_parser.add_argument('cmds', choices=['fruits', 'vegetables'])
350
351 @with_argparser(load_parser)
352 @with_category('Command Loading')
353 def do_load(self, ns: argparse.Namespace):
354 """Load Command."""
355 if ns.cmds == 'fruits':
356 try:
357 self.register_command_set(self._fruits)
358 self.poutput('Fruits loaded')
359 except ValueError:
360 self.poutput('Fruits already loaded')
361
362 if ns.cmds == 'vegetables':
363 try:
364 self.register_command_set(self._vegetables)
365 self.poutput('Vegetables loaded')
366 except ValueError:
367 self.poutput('Vegetables already loaded')
368
369 @with_argparser(load_parser)
370 def do_unload(self, ns: argparse.Namespace):
371 """Unload Command."""
372 if ns.cmds == 'fruits':
373 self.unregister_command_set(self._fruits)
374 self.poutput('Fruits unloaded')
375
376 if ns.cmds == 'vegetables':
377 self.unregister_command_set(self._vegetables)
378 self.poutput('Vegetables unloaded')
379
380 cut_parser = cmd2.Cmd2ArgumentParser()
381 cut_parser.add_subparsers(title="item", help="item to cut", metavar="ITEM", required=True)
382
383 @with_argparser(cut_parser)
384 def do_cut(self, ns: argparse.Namespace):
385 """Cut Command."""
386 # Call whatever subcommand function was selected
387 ns.cmd2_subcommand_func(ns)
388
389
390
391 if __name__ == '__main__':
392 app = ExampleApp()
393 app.cmdloop()
394 ```