Skip to content

Commit 73c17db

Browse files
Improved the asyncio-prompt example.
1 parent 7d74972 commit 73c17db

File tree

1 file changed

+21
-15
lines changed

1 file changed

+21
-15
lines changed

examples/prompts/asyncio-prompt.py

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
#!/usr/bin/env python
22
"""
3-
(Python >= 3.5)
3+
(Python >= 3.6)
44
This is an example of how to prompt inside an application that uses the asyncio
55
eventloop. The ``prompt_toolkit`` library will make sure that when other
66
coroutines are writing to stdout, they write above the prompt, not destroying
@@ -19,18 +19,20 @@
1919
from prompt_toolkit.patch_stdout import patch_stdout
2020
from prompt_toolkit.shortcuts import PromptSession
2121

22-
loop = asyncio.get_event_loop()
2322

2423

2524
async def print_counter():
2625
"""
2726
Coroutine that prints counters.
2827
"""
29-
i = 0
30-
while True:
31-
print('Counter: %i' % i)
32-
i += 1
33-
await asyncio.sleep(3)
28+
try:
29+
i = 0
30+
while True:
31+
print('Counter: %i' % i)
32+
i += 1
33+
await asyncio.sleep(3)
34+
except asyncio.CancelledError:
35+
print('Background task cancelled.')
3436

3537

3638
async def interactive_shell():
@@ -49,16 +51,20 @@ async def interactive_shell():
4951
return
5052

5153

52-
def main():
54+
async def main():
5355
with patch_stdout():
54-
shell_task = asyncio.ensure_future(interactive_shell())
55-
background_task = asyncio.gather(print_counter(), return_exceptions=True)
56-
57-
loop.run_until_complete(shell_task)
58-
background_task.cancel()
59-
loop.run_until_complete(background_task)
56+
background_task = asyncio.create_task(print_counter())
57+
try:
58+
await interactive_shell()
59+
finally:
60+
background_task.cancel()
6061
print('Quitting event loop. Bye.')
6162

6263

6364
if __name__ == '__main__':
64-
main()
65+
try:
66+
from asyncio import run
67+
except ImportError:
68+
asyncio.run_until_complete(main())
69+
else:
70+
asyncio.run(main())

0 commit comments

Comments
 (0)