Skip to content

Commit f5f8ac0

Browse files
committed
docs: async call example
1 parent dc05bba commit f5f8ac0

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

examples/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ each:
1717
- Comprehensive example demonstrating various aspects of using
1818
[argparse](https://docs.python.org/3/library/argparse.html) for command argument processing
1919
via the `cmd2.with_argparser` decorator
20+
- [async_call.py](https://github.com/python-cmd2/cmd2/blob/main/examples/async_call.py)
21+
- Shows how to make a call to an async function from a cmd2 command.
2022
- [async_printing.py](https://github.com/python-cmd2/cmd2/blob/main/examples/async_printing.py)
2123
- Shows how to asynchronously print alerts, update the prompt in realtime, and change the window
2224
title

examples/async_call.py

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
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

Comments
 (0)