Debian Codegraph @

examples/command_sets.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """Example revolving around the CommandSet feature for modularizing commands.
3
4 It attempts to cover basic usage as well as more complex usage including dynamic loading and unloading of CommandSets, using
5 CommandSets to add subcommands, as well as how to categorize command in CommandSets. Here we have kept the implementation for
6 most commands trivial because the intent is to focus on the CommandSet feature set.
7
8 The `AutoLoadCommandSet` is a basic command set which is loaded automatically at application startup and stays loaded until
9 application exit. This is the simplest case of simply modularizing command definitions to different classes and/or files.
10
11 The `LoadableFruits` and `LoadableVegetables` CommandSets are dynamically loadable and un-loadable at runtime using the `load`
12 and `unload` commands. This demonstrates the ability to load and unload CommandSets based on application state. Each of these
13 also loads a subcommand of the `cut` command.
14 """
15
16 import argparse
17
18 import cmd2
19 from cmd2 import (
20 CommandSet,
21 CommandSetRegistrationError,
22 with_argparser,
23 with_category,
24 )
25
26 COMMANDSET_BASIC = "Basic CommandSet"
27 COMMANDSET_DYNAMIC = "Dynamic CommandSet"
28 COMMANDSET_LOAD_UNLOAD = "Loading and Unloading CommandSets"
29 COMMANDSET_SUBCOMMAND = "Subcommands with CommandSet"
30
31
32 class AutoLoadCommandSet(CommandSet[cmd2.Cmd]):
33 DEFAULT_CATEGORY = COMMANDSET_BASIC
34
35 def __init__(self) -> None:
36 """CommandSet class for auto-loading commands at startup."""
37 super().__init__()
38
39 def do_hello(self, _: cmd2.Statement) -> None:
40 """Print hello."""
41 self._cmd.poutput("Hello")
42
43 def do_world(self, _: cmd2.Statement) -> None:
44 """Print World."""
45 self._cmd.poutput("World")
46
47
48 class LoadableFruits(CommandSet[cmd2.Cmd]):
49 DEFAULT_CATEGORY = COMMANDSET_DYNAMIC
50
51 def __init__(self) -> None:
52 """CommandSet class for dynamically loading commands related to fruits."""
53 super().__init__()
54
55 def do_apple(self, _: cmd2.Statement) -> None:
56 """Print Apple."""
57 self._cmd.poutput("Apple")
58
59 def do_banana(self, _: cmd2.Statement) -> None:
60 """Print Banana."""
61 self._cmd.poutput("Banana")
62
63 banana_description = "Cut a banana"
64 banana_parser = cmd2.Cmd2ArgumentParser(description=banana_description)
65 banana_parser.add_argument("direction", choices=["discs", "lengthwise"])
66
67 @cmd2.as_subcommand_to("cut", "banana", banana_parser, help=banana_description.lower())
68 def cut_banana(self, ns: argparse.Namespace) -> None:
69 """Cut banana."""
70 self._cmd.poutput("cutting banana: " + ns.direction)
71
72
73 class LoadableVegetables(CommandSet[cmd2.Cmd]):
74 DEFAULT_CATEGORY = COMMANDSET_DYNAMIC
75
76 def __init__(self) -> None:
77 """CommandSet class for dynamically loading commands related to vegetables."""
78 super().__init__()
79
80 def do_arugula(self, _: cmd2.Statement) -> None:
81 "Print Arguula."
82 self._cmd.poutput("Arugula")
83
84 def do_bokchoy(self, _: cmd2.Statement) -> None:
85 """Print Bok Choy."""
86 self._cmd.poutput("Bok Choy")
87
88 bokchoy_description = "Cut some bokchoy"
89 bokchoy_parser = cmd2.Cmd2ArgumentParser(description=bokchoy_description)
90 bokchoy_parser.add_argument("style", choices=["quartered", "diced"])
91
92 @cmd2.as_subcommand_to("cut", "bokchoy", bokchoy_parser, help=bokchoy_description.lower())
93 def cut_bokchoy(self, ns: argparse.Namespace) -> None:
94 """Cut bokchoy."""
95 self._cmd.poutput("Bok Choy: " + ns.style)
96
97
98 class CommandSetApp(cmd2.Cmd):
99 """CommandSets are automatically loaded. Nothing needs to be done."""
100
101 def __init__(self) -> None:
102 """Cmd2 application for demonstrating the CommandSet features."""
103 # This prevents all CommandSets from auto-loading, which is necessary if you don't want some to load at startup
104 super().__init__(auto_load_commands=False)
105
106 self.register_command_set(AutoLoadCommandSet())
107
108 # Store the dynamic CommandSet classes for ease of loading and unloading
109 self._fruits = LoadableFruits()
110 self._vegetables = LoadableVegetables()
111
112 self.intro = "The CommandSet feature allows defining commands in multiple files and the dynamic load/unload at runtime"
113
114 load_parser = cmd2.Cmd2ArgumentParser()
115 load_parser.add_argument("cmds", choices=["fruits", "vegetables"])
116
117 @with_argparser(load_parser)
118 @with_category(COMMANDSET_LOAD_UNLOAD)
119 def do_load(self, ns: argparse.Namespace) -> None:
120 """Load a CommandSet at runtime."""
121 if ns.cmds == "fruits":
122 try:
123 self.register_command_set(self._fruits)
124 self.poutput("Fruits loaded")
125 except CommandSetRegistrationError:
126 self.poutput("Fruits already loaded")
127
128 if ns.cmds == "vegetables":
129 try:
130 self.register_command_set(self._vegetables)
131 self.poutput("Vegetables loaded")
132 except CommandSetRegistrationError:
133 self.poutput("Vegetables already loaded")
134
135 @with_argparser(load_parser)
136 @with_category(COMMANDSET_LOAD_UNLOAD)
137 def do_unload(self, ns: argparse.Namespace) -> None:
138 """Unload a CommandSet at runtime."""
139 if ns.cmds == "fruits":
140 self.unregister_command_set(self._fruits)
141 self.poutput("Fruits unloaded")
142
143 if ns.cmds == "vegetables":
144 self.unregister_command_set(self._vegetables)
145 self.poutput("Vegetables unloaded")
146
147 cut_parser = cmd2.Cmd2ArgumentParser()
148 cut_parser.add_subparsers(title="item", help="item to cut", metavar="ITEM", required=True)
149
150 @with_argparser(cut_parser)
151 @with_category(COMMANDSET_SUBCOMMAND)
152 def do_cut(self, ns: argparse.Namespace) -> None:
153 """Intended to be used with dynamically loaded subcommands specifically."""
154 ns.cmd2_subcommand_func(ns)
155
156
157 if __name__ == "__main__":
158 app = CommandSetApp()
159 app.cmdloop()