1
1
#!/usr/bin/env python
2
2
"""
3
- (Python >= 3.5 )
3
+ (Python >= 3.6 )
4
4
This is an example of how to prompt inside an application that uses the asyncio
5
5
eventloop. The ``prompt_toolkit`` library will make sure that when other
6
6
coroutines are writing to stdout, they write above the prompt, not destroying
19
19
from prompt_toolkit .patch_stdout import patch_stdout
20
20
from prompt_toolkit .shortcuts import PromptSession
21
21
22
- loop = asyncio .get_event_loop ()
23
22
24
23
25
24
async def print_counter ():
26
25
"""
27
26
Coroutine that prints counters.
28
27
"""
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.' )
34
36
35
37
36
38
async def interactive_shell ():
@@ -49,16 +51,20 @@ async def interactive_shell():
49
51
return
50
52
51
53
52
- def main ():
54
+ async def main ():
53
55
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 ()
60
61
print ('Quitting event loop. Bye.' )
61
62
62
63
63
64
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