|
| 1 | +#!/usr/bin/env python |
| 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 | + """ |
| 16 | + Await a coroutine from a synchronous function/method. |
| 17 | + """ |
| 18 | + |
| 19 | + global _event_loop |
| 20 | + |
| 21 | + if _event_loop is None: |
| 22 | + with _event_lock: |
| 23 | + if _event_loop is None: |
| 24 | + _event_loop = asyncio.new_event_loop() |
| 25 | + thread = threading.Thread( |
| 26 | + target=_event_loop.run_forever, |
| 27 | + name='Async Runner', |
| 28 | + daemon=True, |
| 29 | + ) |
| 30 | + thread.start() |
| 31 | + |
| 32 | + return asyncio.run_coroutine_threadsafe(coro, _event_loop) |
| 33 | + |
| 34 | +async def async_wait(duration: float) -> float: |
| 35 | + """ |
| 36 | + Example async function that is called from a synchronous cmd2 command |
| 37 | + """ |
| 38 | + await asyncio.sleep(duration) |
| 39 | + return duration |
| 40 | + |
| 41 | + |
| 42 | +class AsyncCallExample(cmd2.Cmd): |
| 43 | + """ |
| 44 | + A simple cmd2 application. |
| 45 | + Demonstrates how to run an async function from a cmd2 command. |
| 46 | + """ |
| 47 | + |
| 48 | + def do_async_wait(self, _: str) -> None: |
| 49 | + """ |
| 50 | + Waits asynchronously. Example cmd2 command that calls an async function. |
| 51 | + """ |
| 52 | + |
| 53 | + waitable = run_async(async_wait(0.1)) |
| 54 | + self.poutput('Begin waiting...') |
| 55 | + # Wait for coroutine to complete and get its return value: |
| 56 | + res = waitable.result() |
| 57 | + self.poutput(f'Done waiting: {res}') |
| 58 | + return |
| 59 | + |
| 60 | + def do_hello_world(self, _: str) -> None: |
| 61 | + """ |
| 62 | + Prints a simple greeting. Just a typical (synchronous) cmd2 command |
| 63 | + """ |
| 64 | + self.poutput('Hello World') |
| 65 | + |
| 66 | + |
| 67 | +async def main() -> int: |
| 68 | + """ |
| 69 | + Having this async ensures presence of the top level event loop. |
| 70 | + """ |
| 71 | + app = AsyncCallExample() |
| 72 | + app.set_window_title("Call to an Async Function Test") |
| 73 | + return app.cmdloop() |
| 74 | + |
| 75 | + |
| 76 | +if __name__ == '__main__': |
| 77 | + import sys |
| 78 | + sys.exit(asyncio.run(main(), debug=True)) |
0 commit comments