Debian Codegraph @

examples/async_commands.py

raw symbols SCIP
1 #!/usr/bin/env python
2 """A simple example demonstrating how to run async commands in a cmd2 app.
3
4 It also demonstrates how to configure keybindings to run a handler method on
5 key-combo press and how to display colored output above the prompt.
6 """
7
8 import asyncio
9 import functools
10 import secrets
11 import shutil
12 import threading
13 from collections.abc import Callable
14 from typing import (
15 Any,
16 )
17
18 from prompt_toolkit import ANSI, print_formatted_text
19 from prompt_toolkit.key_binding import KeyBindings
20 from rich.text import Text
21
22 import cmd2
23
24 # Global event loop and lock
25 _event_loop: asyncio.AbstractEventLoop | None = None
26 _event_lock = threading.Lock()
27
28
29 def _get_event_loop() -> asyncio.AbstractEventLoop:
30 """Get or create the background event loop."""
31 global _event_loop # noqa: PLW0603
32
33 if _event_loop is None:
34 with _event_lock:
35 if _event_loop is None:
36 _event_loop = asyncio.new_event_loop()
37 thread = threading.Thread(
38 target=_event_loop.run_forever,
39 name="Async Runner",
40 daemon=True,
41 )
42 thread.start()
43 return _event_loop
44
45
46 def with_async_loop(func: Callable[..., Any], cancel_on_interrupt: bool = True) -> Callable[..., Any]:
47 """Decorate an async ``do_*`` command method to give it access to the event loop.
48
49 This decorator wraps a do_* command method. When the command is executed,
50 it submits the coroutine returned by the method to a background asyncio loop
51 and waits for the result synchronously (blocking the cmd2 loop, as expected
52 for a synchronous command).
53
54 :param func: do_* method to wrap
55 :param cancel_on_interrupt: if True, cancel any running async task on an interrupt;
56 if False, leave any async task running
57 """
58
59 @functools.wraps(func)
60 def wrapper(self: cmd2.Cmd, *args: Any, **kwargs: Any) -> Any:
61 loop = _get_event_loop()
62 coro = func(self, *args, **kwargs)
63 future = asyncio.run_coroutine_threadsafe(coro, loop)
64 try:
65 return future.result()
66 except KeyboardInterrupt:
67 if cancel_on_interrupt:
68 future.cancel()
69 raise
70
71 return wrapper
72
73
74 class AsyncCommandsApp(cmd2.Cmd):
75 """Example cmd2 application with async commands."""
76
77 def __init__(self) -> None:
78 super().__init__()
79 self.intro = 'Welcome to the Async Commands example. Type "help" to see available commands.'
80
81 # Create an instance of SystemRandom
82 self._secure_generator = secrets.SystemRandom()
83
84 if self.main_session.key_bindings is None:
85 self.main_session.key_bindings = KeyBindings()
86
87 # Add a custom key binding for <CTRL>+T that calls a method so it has access to self
88 @self.main_session.key_bindings.add("c-t")
89 def _(_event: Any) -> None:
90 self.handle_control_t(_event)
91
92 @with_async_loop
93 async def do_my_async(self, _: cmd2.Statement) -> None:
94 """An example async command that simulates work."""
95 self.poutput("Starting async work...")
96 # simulate some async I/O
97 await asyncio.sleep(1.0)
98 self.poutput("Async work complete!")
99
100 @with_async_loop
101 async def do_fetch(self, _: cmd2.Statement) -> None:
102 """Simulate fetching data asynchronously."""
103 self.poutput("Fetching data...")
104 data = await self._fake_fetch()
105 self.poutput(f"Received: {data}")
106
107 async def _fake_fetch(self) -> str:
108 await asyncio.sleep(0.5)
109 return "Some Data"
110
111 def do_sync_command(self, _: cmd2.Statement) -> None:
112 """A normal synchronous command."""
113 self.poutput("This is a normal synchronous command.")
114
115 def handle_control_t(self, _event) -> None:
116 """Handler method for <CTRL>+T key press.
117
118 Prints 'fnord' above the prompt in a random color and random position.
119 """
120 word = "fnord"
121
122 # Generate a random RGB color tuple
123 r = self._secure_generator.randint(0, 255)
124 g = self._secure_generator.randint(0, 255)
125 b = self._secure_generator.randint(0, 255)
126
127 # Get terminal width to calculate padding for right-alignment
128 cols, _ = shutil.get_terminal_size()
129 extra_width = cols - len(word) - 1
130 padding_size = self._secure_generator.randint(0, extra_width)
131 padding = " " * padding_size
132
133 # Use rich to generate the overall text to print out
134 text = Text()
135 text.append(padding)
136 text.append(word, style=f"rgb({r},{g},{b})")
137
138 print_formatted_text(ANSI(cmd2.rich_utils.rich_text_to_string(text)))
139
140
141 if __name__ == "__main__":
142 import sys
143
144 app = AsyncCommandsApp()
145 sys.exit(app.cmdloop())