1
1
#!/usr/bin/env python
2
2
"""
3
- (Python >3.3)
4
-
3
+ (Python >= 3.5)
5
4
This is an example of how to embed a CommandLineInterface inside an application
6
5
that uses the asyncio eventloop. The ``prompt_toolkit`` library will make sure
7
6
that when other coroutines are writing to stdout, they write above the prompt,
8
7
not destroying the input line.
9
-
10
8
This example does several things:
11
9
1. It starts a simple coroutine, printing a counter to stdout every second.
12
10
2. It starts a simple input/echo cli loop which reads from stdin.
13
-
14
11
Very important is the following patch. If you are passing stdin by reference to
15
12
other parts of the code, make sure that this patch is applied as early as
16
13
possible. ::
17
-
18
14
sys.stdout = cli.stdout_proxy()
19
15
"""
20
- from __future__ import unicode_literals
16
+
21
17
from prompt_toolkit .interface import CommandLineInterface
22
18
from prompt_toolkit .shortcuts import create_prompt_application , create_asyncio_eventloop
23
19
24
20
import asyncio
25
21
import sys
26
22
27
-
28
23
loop = asyncio .get_event_loop ()
29
24
30
25
31
- @asyncio .coroutine
32
- def print_counter ():
26
+ async def print_counter ():
33
27
"""
34
28
Coroutine that prints counters.
35
29
"""
36
30
i = 0
37
31
while True :
38
32
print ('Counter: %i' % i )
39
33
i += 1
40
- yield from asyncio .sleep (3 )
34
+ try :
35
+ await asyncio .sleep (3 )
36
+ except asyncio .CancelledError :
37
+ return
41
38
42
39
43
- @asyncio .coroutine
44
- def interactive_shell ():
40
+ async def interactive_shell ():
45
41
"""
46
42
Coroutine that shows the interactive command line.
47
43
"""
@@ -61,19 +57,20 @@ def interactive_shell():
61
57
# Run echo loop. Read text from stdin, and reply it back.
62
58
while True :
63
59
try :
64
- result = yield from cli .run_async ()
65
- print ('You said: "%s" \n ' % result .text )
60
+ result = await cli .run_async ()
61
+ print ('You said: "{0}"' . format ( result .text ) )
66
62
except (EOFError , KeyboardInterrupt ):
67
- loop .stop ()
68
- print ('Qutting event loop. Bye.' )
69
63
return
70
64
71
65
72
66
def main ():
73
- asyncio .async (print_counter ())
74
- asyncio .async (interactive_shell ())
75
-
76
- loop .run_forever ()
67
+ counter = loop .create_task (print_counter ())
68
+ shell = loop .create_task (interactive_shell ())
69
+
70
+ loop .run_until_complete (shell )
71
+ counter .cancel ()
72
+ loop .run_until_complete (counter )
73
+ print ('Qutting event loop. Bye.' )
77
74
loop .close ()
78
75
79
76
0 commit comments