Skip to content
This repository was archived by the owner on May 31, 2021. It is now read-only.

Commit db0dcad

Browse files
author
Vincent Michel
committed
Update examples to promote the use of a main coroutine
1 parent 3be7659 commit db0dcad

13 files changed

+99
-55
lines changed

examples/asyncio_deferred.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,5 @@ async def steps(x):
1313

1414

1515
loop = asyncio.get_event_loop()
16-
coro = steps(5)
17-
loop.run_until_complete(coro)
16+
loop.run_until_complete(steps(5))
1817
loop.close()
19-

examples/create_task.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
11
import asyncio
22

3+
34
async def say(what, when):
45
await asyncio.sleep(when)
56
print(what)
67

78

8-
loop = asyncio.get_event_loop()
9+
async def schedule():
10+
asyncio.ensure_future(say('first hello', 2))
11+
asyncio.ensure_future(say('second hello', 1))
912

10-
loop.create_task(say('first hello', 2))
11-
loop.create_task(say('second hello', 1))
1213

14+
loop = asyncio.get_event_loop()
15+
loop.run_until_complete(schedule())
1316
loop.run_forever()
1417
loop.close()

examples/hello_clock.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33

44
async def print_every_second():
5-
"Print seconds"
65
while True:
76
for i in range(60):
87
print(i, 's')
@@ -15,9 +14,12 @@ async def print_every_minute():
1514
print(i, 'minute')
1615

1716

17+
async def main():
18+
coro_second = print_every_second()
19+
coro_minute = print_every_minute()
20+
await asyncio.gather(coro_second, coro_minute)
21+
22+
1823
loop = asyncio.get_event_loop()
19-
loop.run_until_complete(
20-
asyncio.gather(print_every_second(),
21-
print_every_minute())
22-
)
24+
loop.run_until_complete(main())
2325
loop.close()

examples/hello_world.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import asyncio
22

3+
34
async def say(what, when):
45
await asyncio.sleep(when)
56
print(what)
67

8+
79
loop = asyncio.get_event_loop()
810
loop.run_until_complete(say('hello world', 1))
911
loop.close()

examples/http_client.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,20 @@
11
import asyncio
22
import aiohttp
33

4+
45
async def fetch_page(session, url):
56
with aiohttp.Timeout(10):
67
async with session.get(url) as response:
78
assert response.status == 200
89
return await response.read()
910

11+
12+
async def main():
13+
with aiohttp.ClientSession() as session:
14+
content = await fetch_page(session, 'http://python.org')
15+
print(content.decode())
16+
17+
1018
loop = asyncio.get_event_loop()
11-
with aiohttp.ClientSession() as session:
12-
content = loop.run_until_complete(
13-
fetch_page(session, 'http://python.org'))
14-
print(content)
19+
loop.run_until_complete(main())
1520
loop.close()

examples/loop_stop.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,24 @@
11
import asyncio
22

3+
34
async def say(what, when):
45
await asyncio.sleep(when)
56
print(what)
67

7-
async def stop_after(loop, when):
8+
9+
async def stop_after(when):
810
await asyncio.sleep(when)
9-
loop.stop()
11+
asyncio.get_event_loop().stop()
1012

1113

12-
loop = asyncio.get_event_loop()
14+
async def schedule():
15+
asyncio.ensure_future(say('first hello', 2))
16+
asyncio.ensure_future(say('second hello', 1))
17+
asyncio.ensure_future(say('third hello', 4))
18+
asyncio.ensure_future(stop_after(3))
1319

14-
loop.create_task(say('first hello', 2))
15-
loop.create_task(say('second hello', 1))
16-
loop.create_task(say('third hello', 4))
17-
loop.create_task(stop_after(loop, 3))
1820

21+
loop = asyncio.get_event_loop()
22+
loop.run_until_complete(schedule())
1923
loop.run_forever()
2024
loop.close()

examples/producer_consumer.py

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,13 @@
33

44

55
async def produce(queue, n):
6-
for x in range(1, n + 1):
7-
# produce an item
6+
# produce n items
7+
for x in range(1, n+1):
8+
9+
# produce an item (simulate i/o operation using sleep)
810
print('producing {}/{}'.format(x, n))
9-
# simulate i/o operation using sleep
10-
await asyncio.sleep(random.random())
11-
item = str(x)
11+
item = await asyncio.sleep(random.random(), result=x)
12+
1213
# put the item in the queue
1314
await queue.put(item)
1415

@@ -20,19 +21,23 @@ async def consume(queue):
2021
while True:
2122
# wait for an item from the producer
2223
item = await queue.get()
24+
25+
# the producer emits None to indicate that it is done
2326
if item is None:
24-
# the producer emits None to indicate that it is done
2527
break
2628

27-
# process the item
29+
# process the item (simulate i/o operation using sleep)
2830
print('consuming item {}...'.format(item))
29-
# simulate i/o operation using sleep
3031
await asyncio.sleep(random.random())
3132

3233

34+
async def main():
35+
queue = asyncio.Queue()
36+
producer_coro = produce(queue, 10)
37+
consumer_coro = consume(queue)
38+
await asyncio.gather(producer_coro, consumer_coro)
39+
40+
3341
loop = asyncio.get_event_loop()
34-
queue = asyncio.Queue()
35-
producer_coro = produce(queue, 10)
36-
consumer_coro = consume(queue)
37-
loop.run_until_complete(asyncio.gather(producer_coro, consumer_coro))
42+
loop.run_until_complete(main())
3843
loop.close()

examples/producer_consumer_join.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,28 +17,26 @@ async def consume(queue):
1717
while True:
1818
# wait for an item from the producer
1919
item = await queue.get()
20-
2120
# process the item
2221
print('consuming {}...'.format(item))
2322
# simulate i/o operation using sleep
2423
await asyncio.sleep(random.random())
25-
2624
# Notify the queue that the item has been processed
2725
queue.task_done()
2826

2927

30-
async def run(n):
28+
async def main():
3129
queue = asyncio.Queue()
3230
# schedule the consumer
3331
consumer = asyncio.ensure_future(consume(queue))
3432
# run the producer and wait for completion
35-
await produce(queue, n)
33+
await produce(queue, 10)
3634
# wait until the consumer has processed all items
3735
await queue.join()
3836
# the consumer is still awaiting for an item, cancel it
3937
consumer.cancel()
4038

4139

4240
loop = asyncio.get_event_loop()
43-
loop.run_until_complete(run(10))
41+
loop.run_until_complete(main())
4442
loop.close()

examples/run_in_thread.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import asyncio
22

3+
34
def compute_pi(digits):
4-
# implementation
5+
# CPU-intensive computation
56
return 3.14
67

78

examples/subprocess_command.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,27 @@ async def run_command(*args):
55
# Create subprocess
66
process = await asyncio.create_subprocess_exec(
77
*args,
8-
# stdout must a pipe to be accessible as process.stdout
8+
# stdout must be piped to be accessible as process.stdout
99
stdout=asyncio.subprocess.PIPE)
10+
1011
# Wait for the subprocess to finish
1112
stdout, stderr = await process.communicate()
13+
1214
# Return stdout
1315
return stdout.decode().strip()
1416

1517

18+
async def main():
19+
# Gather uname and date commands
20+
commands = asyncio.gather(run_command('uname'), run_command('date'))
21+
22+
# Wait for the results
23+
uname, date = await commands
24+
25+
# Print a report
26+
print('uname: {}, date: {}'.format(uname, date))
27+
28+
1629
loop = asyncio.get_event_loop()
17-
# Gather uname and date commands
18-
commands = asyncio.gather(run_command('uname'), run_command('date'))
19-
# Run the commands
20-
uname, date = loop.run_until_complete(commands)
21-
# Print a report
22-
print('uname: {}, date: {}'.format(uname, date))
30+
loop.run_until_complete(main())
2331
loop.close()

examples/subprocess_echo.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,16 @@ async def echo(msg):
99
stdin=asyncio.subprocess.PIPE,
1010
# stdout must a pipe to be accessible as process.stdout
1111
stdout=asyncio.subprocess.PIPE)
12+
1213
# Write message
1314
print('Writing {!r} ...'.format(msg))
1415
process.stdin.write(msg.encode() + b'\n')
16+
1517
# Read reply
1618
data = await process.stdout.readline()
1719
reply = data.decode().strip()
1820
print('Received {!r}'.format(reply))
21+
1922
# Stop the subprocess
2023
process.terminate()
2124
code = await process.wait()

examples/tcp_echo_client.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import asyncio
22

33

4-
async def tcp_echo_client(message, loop):
4+
async def tcp_echo_client(message):
55
reader, writer = await asyncio.open_connection('127.0.0.1', 8888)
66

77
print('Send: %r' % message)
@@ -14,7 +14,11 @@ async def tcp_echo_client(message, loop):
1414
writer.close()
1515

1616

17-
message = 'Hello World!'
17+
async def main():
18+
message = 'Hello World!'
19+
await tcp_echo_client(message)
20+
21+
1822
loop = asyncio.get_event_loop()
19-
loop.run_until_complete(tcp_echo_client(message, loop))
23+
loop.run_until_complete(main())
2024
loop.close()

examples/tcp_echo_server.py

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import asyncio
22

3+
34
async def handle_echo(reader, writer):
45
data = await reader.read(100)
56
message = data.decode()
@@ -13,18 +14,28 @@ async def handle_echo(reader, writer):
1314
print("Close the client socket")
1415
writer.close()
1516

17+
18+
async def start_serving():
19+
server = await asyncio.start_server(handle_echo, '127.0.0.1', 8888)
20+
print('Serving on {}'.format(server.sockets[0].getsockname()))
21+
return stop_serving(server)
22+
23+
24+
async def stop_serving(server):
25+
server.close()
26+
await server.wait_closed()
27+
28+
29+
# Start the server
1630
loop = asyncio.get_event_loop()
17-
coro = asyncio.start_server(handle_echo, '127.0.0.1', 8888)
18-
server = loop.run_until_complete(coro)
31+
stop_coro = loop.run_until_complete(start_serving())
1932

2033
# Serve requests until Ctrl+C is pressed
21-
print('Serving on {}'.format(server.sockets[0].getsockname()))
2234
try:
2335
loop.run_forever()
2436
except KeyboardInterrupt:
2537
pass
2638

2739
# Close the server
28-
server.close()
29-
loop.run_until_complete(server.wait_closed())
40+
loop.run_until_complete(stop_coro)
3041
loop.close()

0 commit comments

Comments
 (0)