| 1 | # Async Commands |
| 2 | |
| 3 | `cmd2` is built on top of the Python Standard Library's `cmd` module, which is inherently |
| 4 | synchronous. This means that `do_*` command methods are expected to be synchronous functions. |
| 5 | |
| 6 | However, you can still integrate asynchronous code (using `asyncio` and `async`/`await`) into your |
| 7 | `cmd2` application by running an `asyncio` event loop in a background thread and bridging calls to |
| 8 | it. |
| 9 | |
| 10 | ## The `with_async_loop` Decorator |
| 11 | |
| 12 | A clean way to handle this is to define a decorator that wraps your `async def` commands. This |
| 13 | decorator handles: |
| 14 | |
| 15 | 1. Starting a background thread with an `asyncio` loop (if not already running). |
| 16 | 2. Submitting the command's coroutine to that loop. |
| 17 | 3. Waiting for the result (synchronously) so that the `cmd2` interface behaves as expected |
| 18 | (blocking until the command completes). |
| 19 | |
| 20 | ### Example Implementation |
| 21 | |
| 22 | Here is an example of how to implement such a decorator and use it in your application. |
| 23 | |
| 24 | ```python |
| 25 | import asyncio |
| 26 | import functools |
| 27 | import threading |
| 28 | from typing import Any, Callable |
| 29 | import cmd2 |
| 30 | |
| 31 | # Global event loop and lock |
| 32 | _event_loop = None |
| 33 | _event_lock = threading.Lock() |
| 34 | |
| 35 | def _get_event_loop() -> asyncio.AbstractEventLoop: |
| 36 | """Get or create the background event loop.""" |
| 37 | global _event_loop |
| 38 | |
| 39 | if _event_loop is None: |
| 40 | with _event_lock: |
| 41 | if _event_loop is None: |
| 42 | _event_loop = asyncio.new_event_loop() |
| 43 | thread = threading.Thread( |
| 44 | target=_event_loop.run_forever, |
| 45 | name='Async Runner', |
| 46 | daemon=True, |
| 47 | ) |
| 48 | thread.start() |
| 49 | return _event_loop |
| 50 | |
| 51 | def with_async_loop(func: Callable[..., Any]) -> Callable[..., Any]: |
| 52 | """Decorator to run a command method asynchronously in a background thread.""" |
| 53 | @functools.wraps(func) |
| 54 | def wrapper(self: cmd2.Cmd, *args: Any, **kwargs: Any) -> Any: |
| 55 | loop = _get_event_loop() |
| 56 | coro = func(self, *args, **kwargs) |
| 57 | future = asyncio.run_coroutine_threadsafe(coro, loop) |
| 58 | return future.result() |
| 59 | return wrapper |
| 60 | |
| 61 | class AsyncApp(cmd2.Cmd): |
| 62 | @with_async_loop |
| 63 | async def do_my_async(self, _: cmd2.Statement) -> None: |
| 64 | self.poutput("Starting async work...") |
| 65 | await asyncio.sleep(1.0) |
| 66 | self.poutput("Async work complete!") |
| 67 | ``` |
| 68 | |
| 69 | ## See Also |
| 70 | |
| 71 | - [async_commands.py](https://github.com/python-cmd2/cmd2/blob/main/examples/async_commands.py) - |
| 72 | Full example code. |
| 73 | - [async_call.py](https://github.com/python-cmd2/cmd2/blob/main/examples/async_call.py) - An |
| 74 | alternative example showing how to make individual async calls without a decorator. |