| 1 |
|
| 2 |
"""A simple example demonstrating calling an async function from a cmd2 app.""" |
| 3 |
|
| 4 |
import asyncio |
| 5 |
import concurrent.futures |
| 6 |
import threading |
| 7 |
|
| 8 |
import cmd2 |
| 9 |
|
| 10 |
_event_loop = None |
| 11 |
_event_lock = threading.Lock() |
| 12 |
|
| 13 |
|
| 14 |
def run_async(coro) -> concurrent.futures.Future: |
| 15 |
"""Await a coroutine from a synchronous function/method.""" |
| 16 |
global _event_loop |
| 17 |
|
| 18 |
if _event_loop is None: |
| 19 |
with _event_lock: |
| 20 |
if _event_loop is None: |
| 21 |
_event_loop = asyncio.new_event_loop() |
| 22 |
thread = threading.Thread( |
| 23 |
target=_event_loop.run_forever, |
| 24 |
name="Async Runner", |
| 25 |
daemon=True, |
| 26 |
) |
| 27 |
thread.start() |
| 28 |
|
| 29 |
return asyncio.run_coroutine_threadsafe(coro, _event_loop) |
| 30 |
|
| 31 |
|
| 32 |
async def async_wait(duration: float) -> float: |
| 33 |
"""Example async function that is called from a synchronous cmd2 command.""" |
| 34 |
await asyncio.sleep(duration) |
| 35 |
return duration |
| 36 |
|
| 37 |
|
| 38 |
class AsyncCallExample(cmd2.Cmd): |
| 39 |
"""A simple cmd2 application. |
| 40 |
|
| 41 |
Demonstrates how to run an async function from a cmd2 command. |
| 42 |
""" |
| 43 |
|
| 44 |
def do_async_wait(self, _: str) -> None: |
| 45 |
"""Waits asynchronously. |
| 46 |
|
| 47 |
Example cmd2 command that calls an async function. |
| 48 |
""" |
| 49 |
waitable = run_async(async_wait(0.1)) |
| 50 |
self.poutput("Begin waiting...") |
| 51 |
|
| 52 |
res = waitable.result() |
| 53 |
self.poutput(f"Done waiting: {res}") |
| 54 |
return |
| 55 |
|
| 56 |
def do_hello_world(self, _: str) -> None: |
| 57 |
"""Prints a simple greeting. |
| 58 |
|
| 59 |
Just a typical (synchronous) cmd2 command |
| 60 |
""" |
| 61 |
self.poutput("Hello World") |
| 62 |
|
| 63 |
|
| 64 |
def main() -> int: |
| 65 |
"""Main entry point for the example.""" |
| 66 |
app = AsyncCallExample() |
| 67 |
app.set_window_title("Call to an Async Function Test") |
| 68 |
return app.cmdloop() |
| 69 |
|
| 70 |
|
| 71 |
if __name__ == "__main__": |
| 72 |
import sys |
| 73 |
|
| 74 |
sys.exit(main()) |