Debian Codegraph @

examples/default_categories.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """Example demonstrating the DEFAULT_CATEGORY class variable for Cmd and CommandSet.
3
4 In cmd2 4.0, command categorization is driven by the DEFAULT_CATEGORY class variable.
5 This example shows:
6 1. How a Cmd class defines its own default category.
7 2. How a CommandSet defines its own default category.
8 3. How overriding a framework command moves it to the child class's category.
9 4. How to use @with_category to manually override the automatic categorization.
10 """
11
12 import argparse
13
14 import cmd2
15 from cmd2 import (
16 CommandSet,
17 with_argparser,
18 with_category,
19 )
20
21
22 class MyPlugin(CommandSet[cmd2.Cmd]):
23 """A CommandSet that defines its own category."""
24
25 DEFAULT_CATEGORY = "Plugin Commands"
26
27 def do_plugin_action(self, _: cmd2.Statement) -> None:
28 """A command defined in a CommandSet."""
29 self._cmd.poutput("Plugin action executed")
30
31
32 class CategoryApp(cmd2.Cmd):
33 """An application demonstrating various categorization scenarios."""
34
35 # This sets the default category for all commands defined in this class
36 DEFAULT_CATEGORY = "Application Commands"
37
38 # This overrides the category for the cmd2 built-in commands
39 cmd2.Cmd.DEFAULT_CATEGORY = "Cmd2 Shell Commands"
40
41 def __init__(self) -> None:
42 super().__init__()
43 # Register a command set to show how its categories integrate
44 self.register_command_set(MyPlugin())
45
46 def do_app_command(self, _: cmd2.Statement) -> None:
47 """A standard command defined in the child class."""
48 self.poutput("Application command executed")
49
50 @with_argparser(cmd2.Cmd._build_quit_parser)
51 def do_quit(self, args: argparse.Namespace) -> bool | None:
52 """Overriding a built-in command without a decorator moves it to our category."""
53 return super().do_quit(args.cmd2_statement)
54
55 @with_category(cmd2.Cmd.DEFAULT_CATEGORY)
56 @with_argparser(cmd2.Cmd._build_shortcuts_parser)
57 def do_shortcuts(self, args: argparse.Namespace) -> None:
58 """Overriding with @with_category(cmd2.Cmd.DEFAULT_CATEGORY) keeps it cmd2's category."""
59 super().do_shortcuts(args.cmd2_statement)
60
61
62 if __name__ == "__main__":
63 import sys
64
65 app = CategoryApp()
66 app.poutput("Type 'help' to see how the commands are categorized.\n")
67 sys.exit(app.cmdloop())