Debian Codegraph @

examples/getting_started.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """An example cmd2 application demonstrating many common features.
3
4 Features demonstrated include all of the following:
5 1) Colorizing/stylizing output
6 2) Persistent history
7 3) How to run an initialization script at startup
8 4) How to group and categorize commands when displaying them in help
9 5) Opting-in to using the ipy command to run an IPython shell
10 6) Allowing access to your application in py and ipy
11 7) Displaying an intro banner upon starting your application
12 8) Using a custom prompt
13 9) How to make custom attributes settable at runtime
14 10) Shortcuts for commands
15 11) Persistent bottom toolbar with realtime status updates
16 12) Right prompt which displays contextual information
17 13) Background thread to update the content displayed by the bottom toolbar outside of the UI thread to keep things responsive
18 14) Using preloop() and postloop() hooks to start and stop a background thread
19 15) Using the with_annotated decorator to parse typed command arguments
20 16) Using the with_argparser decorator to parse command arguments with a custom parser
21 """
22
23 import argparse
24 import datetime
25 import pathlib
26 import sys
27 import threading
28 from typing import Annotated
29
30 from prompt_toolkit.application import get_app
31 from prompt_toolkit.formatted_text import AnyFormattedText
32 from rich.style import Style
33 from rich.text import Text
34
35 import cmd2
36 from cmd2 import (
37 Color,
38 stylize,
39 )
40 from cmd2.annotated import Option
41
42
43 class BasicApp(cmd2.Cmd):
44 """Cmd2 application to demonstrate many common features."""
45
46 DEFAULT_CATEGORY = "My Custom Commands"
47
48 def __init__(self) -> None:
49 """Initialize the cmd2 application."""
50 # Startup script that defines a couple aliases for running shell commands
51 alias_script = pathlib.Path(__file__).absolute().parent / ".cmd2rc"
52
53 # Create a shortcut for one of our commands
54 shortcuts = cmd2.DEFAULT_SHORTCUTS
55 shortcuts.update({"&": "intro"})
56
57 super().__init__(
58 auto_suggest=True,
59 enable_bottom_toolbar=True,
60 enable_rprompt=True,
61 include_ipy=True,
62 persistent_history_file="cmd2_history.dat",
63 refresh_interval=0.5, # refresh the UI twice a second to keep the bottom toolbar timestamp current
64 shortcuts=shortcuts,
65 startup_script=str(alias_script),
66 )
67
68 # Prints an intro banner once upon application startup
69 self.intro = (
70 stylize(
71 "Welcome to cmd2!",
72 style=Style(color=Color.GREEN1, bgcolor=Color.GRAY0, bold=True),
73 )
74 + " Note the full Unicode support: 😇 💩"
75 + " and the persistent bottom bar with realtime status updates!"
76 )
77
78 # Show this as the prompt when asking for input
79 self.prompt = "myapp> "
80
81 # Allow access to your application in py and ipy via self
82 self.self_in_py = True
83
84 # Color to output text in with echo command
85 self.foreground_color = Color.CYAN.value
86
87 # Make echo_fg settable at runtime
88 fg_colors = [c.value for c in Color]
89 self.add_settable(
90 cmd2.Settable(
91 "foreground_color",
92 str,
93 Text.assemble(
94 "Foreground color to use with echo command ",
95 "(Options: ",
96 Text("Green", Style(color=Color.GREEN)),
97 ", ",
98 Text("Red", Style(color=Color.RED)),
99 ", ",
100 Text("Blue", Style(color=Color.BLUE)),
101 ", ...)",
102 ),
103 self,
104 choices=fg_colors,
105 )
106 )
107
108 # Initialize background thread state for the bottom toolbar
109 self._toolbar_state = {"now": ""}
110 self._toolbar_lock = threading.Lock()
111 self._stop_thread_event = threading.Event()
112 self._toolbar_thread: threading.Thread | None = None
113
114 def _update_toolbar_state(self) -> None:
115 """Background thread worker to update toolbar state continuously."""
116 while not self._stop_thread_event.is_set():
117 # Get the current time in ISO format with 0.01s precision
118 dt = datetime.datetime.now(datetime.timezone.utc).astimezone()
119 now = dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-4] + dt.strftime("%z")
120
121 with self._toolbar_lock:
122 self._toolbar_state["now"] = now
123
124 # Sleep to yield CPU, polling 4 times a second
125 self._stop_thread_event.wait(0.25)
126
127 def preloop(self) -> None:
128 """Hook method executed once when the cmdloop() method is called."""
129 self._stop_thread_event.clear()
130 self._toolbar_thread = threading.Thread(target=self._update_toolbar_state, daemon=True)
131 self._toolbar_thread.start()
132
133 def postloop(self) -> None:
134 """Hook method executed once when the cmdloop() method is about to return."""
135 if self._toolbar_thread and self._toolbar_thread.is_alive():
136 self._stop_thread_event.set()
137 self._toolbar_thread.join()
138
139 def get_bottom_toolbar(self) -> AnyFormattedText:
140 left_text = sys.argv[0]
141
142 with self._toolbar_lock:
143 now = self._toolbar_state.get("now", "")
144
145 # Fetch the terminal width to calculate padding for right-alignment.
146 # If called outside a running app loop (e.g., in unit tests), get_app()
147 # safely returns a dummy app with an 80-column fallback.
148 cols = get_app().output.get_size().columns
149 padding_size = cols - len(left_text) - len(now)
150 if padding_size < 1:
151 padding_size = 1
152 padding = " " * padding_size
153
154 # Return formatted text for prompt-toolkit
155 return [
156 ("ansigreen", left_text),
157 ("", padding),
158 ("ansicyan", now),
159 ]
160
161 def get_rprompt(self) -> AnyFormattedText:
162 current_working_directory = pathlib.Path.cwd()
163 style = "bg:ansired fg:ansiwhite"
164 text = f"cwd={current_working_directory}"
165 return [(style, text)]
166
167 @cmd2.with_annotated
168 def do_cat(
169 self,
170 path: pathlib.Path, # Required positional argument with type annotation, tab-completes filesystem paths automatically
171 numbered: Annotated[ # Optional flag argument with type annotation, default value, and help text
172 bool, Option("-n", "--number", help_text="prefix each line with its number")
173 ] = False,
174 ) -> None:
175 """Print a file's contents. `path` tab-completes filesystem paths automatically.
176
177 Try:
178 cat <TAB> # path completes files/dirs -- no completer wired
179 cat notes.txt
180 cat notes.txt -n # -n / --number, declared via Option metadata
181 cat notes.txt --no-number
182 """
183 text = path.read_text()
184 lines = text.splitlines()
185 if numbered:
186 numbered_lines = []
187 for index, line in enumerate(lines, start=1):
188 numbered_lines.append(f"{index}: {line}")
189 self.ppaged("\n".join(numbered_lines))
190 else:
191 # Just print the contents using a pager
192 self.ppaged(path.read_text())
193
194 def do_intro(self, _: cmd2.Statement) -> None:
195 """Display the intro banner.
196
197 This command uses raw statement parsing. In general, we strongly recommend against this approach. But since this
198 command effectively takes no arguments, it is safe to use raw statement parsing here.
199
200 The & key is also used as a shortcut for this command, so you can also type & to display the intro banner.
201 """
202 self.poutput(self.intro)
203
204 @staticmethod
205 def _build_echo_parser() -> cmd2.Cmd2ArgumentParser:
206 """Parser factory method for use with the echo command."""
207 echo_parser = cmd2.Cmd2ArgumentParser(description="Command that echoes input.")
208 echo_parser.add_argument("-u", "--upper", action="store_true", help="uppercase the output")
209 echo_parser.add_argument("-r", "--repeat", type=int, default=1, help="output [n] times")
210 echo_parser.add_argument("words", nargs="+", help="words to print")
211 return echo_parser
212
213 @cmd2.with_argparser(_build_echo_parser)
214 def do_echo(self, args: argparse.Namespace) -> None:
215 """Command using with_argparser decorator for parsing arguments."""
216 output_str = " ".join(args.words)
217 if args.upper:
218 output_str = output_str.upper()
219
220 for _ in range(args.repeat):
221 self.poutput(
222 stylize(
223 output_str,
224 style=Style(color=self.foreground_color),
225 )
226 )
227
228
229 if __name__ == "__main__":
230 app = BasicApp()
231 sys.exit(app.cmdloop())