Skip to content

Commit 3deed0a

Browse files
committed
ch21: simplified asyncio examples with modern API
1 parent 06f18c3 commit 3deed0a

File tree

2 files changed

+15
-24
lines changed

2 files changed

+15
-24
lines changed

21-asyncio-py3.7/charfinder/tcp_charfinder.py

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -38,26 +38,19 @@ async def handle_queries(reader, writer): # <3>
3838
# END TCP_CHARFINDER_TOP
3939

4040
# BEGIN TCP_CHARFINDER_MAIN
41-
def main(address='127.0.0.1', port=2323): # <1>
41+
42+
async def main(address='127.0.0.1', port=2323):
4243
port = int(port)
43-
loop = asyncio.get_event_loop()
44-
server_coro = asyncio.start_server(handle_queries, address, port,
45-
loop=loop) # <2>
46-
server = loop.run_until_complete(server_coro) # <3>
44+
server = await asyncio.start_server(
45+
handle_queries, address, port)
4746

48-
host = server.sockets[0].getsockname() # <4>
49-
print('Serving on {}. Hit CTRL-C to stop.'.format(host)) # <5>
50-
try:
51-
loop.run_forever() # <6>
52-
except KeyboardInterrupt: # CTRL+C pressed
53-
pass
47+
addr = server.sockets[0].getsockname()
48+
print(f'Serving on {addr}. Hit CTRL-C to stop.')
5449

55-
print('Server shutting down.')
56-
server.close() # <7>
57-
loop.run_until_complete(server.wait_closed()) # <8>
58-
loop.close() # <9>
50+
async with server:
51+
await server.serve_forever()
5952

6053

6154
if __name__ == '__main__':
62-
main(*sys.argv[1:]) # <10>
55+
asyncio.run(main(*sys.argv[1:])) # <10>
6356
# END TCP_CHARFINDER_MAIN

21-asyncio-py3.7/countdown.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,12 @@ async def countdown(label, delay):
1717
print(f'{dt:7.4f}s \t{tabs}{label} = {n}')
1818
n -= 1
1919

20-
loop = asyncio.get_event_loop()
21-
tasks = [
22-
loop.create_task(countdown('A', .7)),
23-
loop.create_task(countdown('B', 2)),
24-
loop.create_task(countdown('C', .3)),
25-
loop.create_task(countdown('D', 1)),
20+
coros = [
21+
countdown('A', .7),
22+
countdown('B', 2),
23+
countdown('C', .3),
24+
countdown('D', 1),
2625
]
2726
t0 = time.perf_counter()
28-
loop.run_until_complete(asyncio.wait(tasks))
29-
loop.close()
27+
asyncio.run(asyncio.wait(coros))
3028
print('━' * 50)

0 commit comments

Comments
 (0)