Skip to content

Commit 65a59e0

Browse files
henryiiijonathanslenders
authored andcommitted
Moved example to using Python 3.5 for asyncio
Using `async` and `await`, and removed warnings and depreciated functions (like `asyncio.async`)
1 parent f7aca7b commit 65a59e0

File tree

1 file changed

+17
-20
lines changed

1 file changed

+17
-20
lines changed

examples/asyncio-prompt.py

+17-20
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,43 @@
11
#!/usr/bin/env python
22
"""
3-
(Python >3.3)
4-
3+
(Python >= 3.5)
54
This is an example of how to embed a CommandLineInterface inside an application
65
that uses the asyncio eventloop. The ``prompt_toolkit`` library will make sure
76
that when other coroutines are writing to stdout, they write above the prompt,
87
not destroying the input line.
9-
108
This example does several things:
119
1. It starts a simple coroutine, printing a counter to stdout every second.
1210
2. It starts a simple input/echo cli loop which reads from stdin.
13-
1411
Very important is the following patch. If you are passing stdin by reference to
1512
other parts of the code, make sure that this patch is applied as early as
1613
possible. ::
17-
1814
sys.stdout = cli.stdout_proxy()
1915
"""
20-
from __future__ import unicode_literals
16+
2117
from prompt_toolkit.interface import CommandLineInterface
2218
from prompt_toolkit.shortcuts import create_prompt_application, create_asyncio_eventloop
2319

2420
import asyncio
2521
import sys
2622

27-
2823
loop = asyncio.get_event_loop()
2924

3025

31-
@asyncio.coroutine
32-
def print_counter():
26+
async def print_counter():
3327
"""
3428
Coroutine that prints counters.
3529
"""
3630
i = 0
3731
while True:
3832
print('Counter: %i' % i)
3933
i += 1
40-
yield from asyncio.sleep(3)
34+
try:
35+
await asyncio.sleep(3)
36+
except asyncio.CancelledError:
37+
return
4138

4239

43-
@asyncio.coroutine
44-
def interactive_shell():
40+
async def interactive_shell():
4541
"""
4642
Coroutine that shows the interactive command line.
4743
"""
@@ -61,19 +57,20 @@ def interactive_shell():
6157
# Run echo loop. Read text from stdin, and reply it back.
6258
while True:
6359
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))
6662
except (EOFError, KeyboardInterrupt):
67-
loop.stop()
68-
print('Qutting event loop. Bye.')
6963
return
7064

7165

7266
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.')
7774
loop.close()
7875

7976

0 commit comments

Comments
 (0)