Debian Codegraph @

examples/async_printing.py

raw symbols SCIP
1 #!/usr/bin/env python
2 """A simple example demonstrating an application that asynchronously prints alerts,
3 updates the prompt, and changes the window title.
4 """
5
6 import secrets
7 import threading
8 import time
9 from typing import Any
10
11 from rich.console import Group
12 from rich.panel import Panel
13 from rich.style import Style
14 from rich.table import Table
15 from rich.text import Text
16
17 import cmd2
18 from cmd2 import (
19 Color,
20 stylize,
21 )
22
23
24 def get_alerts() -> list[tuple[Any, bool]]:
25 """Return a list of (alert_msg, soft_wrap) tuples."""
26 table = Table("Command", "Description", title="Quick Help")
27 table.add_row("start_alerts", "Start the async alert generator")
28 table.add_row("stop_alerts", "Stop the async alert generator")
29 table.add_row("help", "Show help menu")
30
31 # Set soft_wrap to False when printing structured Renderables like Tables, Panels, or Columns
32 # to ensure they render as expected. For example, when soft_wrap is True, Panels truncate
33 # text which is wider than the terminal.
34 return [
35 (
36 Text(
37 "Watch as this application prints alerts asynchronously!",
38 style=Style(
39 color=Color.BRIGHT_CYAN,
40 bold=True,
41 ),
42 ),
43 True,
44 ),
45 ("Notice how alerts don't interfere with your typing or cursor location.", True),
46 (
47 Panel(
48 "This message is wrapped in a Rich Panel!",
49 title="System Alert",
50 border_style=Color.BRIGHT_BLUE,
51 expand=False,
52 ),
53 False,
54 ),
55 (table, False),
56 ("You can stop and start the alerts by typing stop_alerts and start_alerts.", True),
57 ]
58
59
60 class AlerterApp(cmd2.Cmd):
61 """An app that shows off add_alert() and set_window_title()."""
62
63 def __init__(self) -> None:
64 """Initialize AlerterApp."""
65 super().__init__()
66
67 self.prompt = "(APR)> "
68
69 # The thread that will asynchronously alert the user of events
70 self._stop_event = threading.Event()
71 self._add_alert_thread = threading.Thread()
72 self._alert_count = 0
73
74 # Create some hooks to handle the starting and stopping of our thread
75 self.register_preloop_hook(self._preloop_hook)
76 self.register_postloop_hook(self._postloop_hook)
77
78 # Create an instance of SystemRandom
79 self._secure_generator = secrets.SystemRandom()
80
81 def _preloop_hook(self) -> None:
82 """Start the alerter thread."""
83 self._stop_event.clear()
84 self._add_alert_thread = threading.Thread(name="alerter", target=self._add_alerts_func)
85 self._add_alert_thread.start()
86
87 def _postloop_hook(self) -> None:
88 """Stop the alerter thread."""
89 self._stop_event.set()
90 if self._add_alert_thread.is_alive():
91 self._add_alert_thread.join()
92
93 def do_start_alerts(self, _: cmd2.Statement) -> None:
94 """Start the alerter thread."""
95 if self._add_alert_thread.is_alive():
96 print("The alert thread is already started")
97 else:
98 self._stop_event.clear()
99 self._add_alert_thread = threading.Thread(name="alerter", target=self._add_alerts_func)
100 self._add_alert_thread.start()
101
102 def do_stop_alerts(self, _: cmd2.Statement) -> None:
103 """Stop the alerter thread."""
104 self._stop_event.set()
105 if self._add_alert_thread.is_alive():
106 self._add_alert_thread.join()
107 else:
108 print("The alert thread is already stopped")
109
110 def _build_colored_prompt(self) -> str:
111 """Randomly build a colored prompt.
112
113 :return: the new prompt.
114 """
115 rand_num = self._secure_generator.randint(1, 6)
116
117 status_color = Color.DEFAULT
118
119 if rand_num == 1:
120 status_color = Color.BRIGHT_RED
121 elif rand_num == 2:
122 status_color = Color.BRIGHT_YELLOW
123 elif rand_num == 3:
124 status_color = Color.CYAN
125 elif rand_num == 4:
126 status_color = Color.BRIGHT_GREEN
127 elif rand_num == 5:
128 status_color = Color.BRIGHT_BLUE
129
130 return stylize(self.visible_prompt, style=status_color)
131
132 def _add_alerts_func(self) -> None:
133 """Print alerts and update the prompt any time the prompt is showing."""
134 self._alert_count = 0
135
136 alerts = get_alerts()
137 alert_index = 0
138 last_alert_time = 0.0
139
140 while not self._stop_event.is_set():
141 cur_time = time.monotonic()
142 alert_msg = None
143 soft_wrap = True
144
145 # Trigger the next alert every 4 seconds
146 if cur_time - last_alert_time >= 4.0:
147 alert_msg, soft_wrap = alerts[alert_index]
148 alert_index = (alert_index + 1) % len(alerts)
149 self._alert_count += 1
150 last_alert_time = cur_time
151
152 # Build a new prompt (color changes randomly)
153 new_prompt = self._build_colored_prompt()
154
155 # Check if we have an alert to print
156 if alert_msg is not None:
157 # Wrap the alert message and an empty string in a Rich Group.
158 # This is a clean way to append a blank line after any RenderableType
159 # (strings, panels, tables, etc.) for visual separation.
160 self.add_alert(
161 msg=Group(alert_msg, ""),
162 soft_wrap=soft_wrap,
163 prompt=new_prompt,
164 )
165
166 new_title = f"Alerts Printed: {self._alert_count}"
167 self.set_window_title(new_title)
168
169 # Otherwise, check if the prompt needs to be updated or refreshed
170 elif self.prompt != new_prompt:
171 self.add_alert(prompt=new_prompt)
172
173 self._stop_event.wait(1.0)
174
175
176 if __name__ == "__main__":
177 import sys
178
179 app = AlerterApp()
180 app.set_window_title("Asynchronous Printer Test")
181 sys.exit(app.cmdloop())