CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: jackfrued/Python-100-Days
Path: blob/master/Day01-15/code/Day13/asyncio3.py
Views: 729
1
"""
2
异步I/O操作 - asyncio模块
3
4
Version: 0.1
5
Author: 骆昊
6
Date: 2018-03-21
7
"""
8
import asyncio
9
10
11
async def wget(host):
12
print('wget %s...' % host)
13
connect = asyncio.open_connection(host, 80)
14
# 异步方式等待连接结果
15
reader, writer = await connect
16
header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host
17
writer.write(header.encode('utf-8'))
18
# 异步I/O方式执行写操作
19
await writer.drain()
20
while True:
21
# 异步I/O方式执行读操作
22
line = await reader.readline()
23
if line == b'\r\n':
24
break
25
print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
26
writer.close()
27
28
29
loop = asyncio.get_event_loop()
30
# 通过生成式语法创建一个装了三个协程的列表
31
hosts_list = ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']
32
tasks = [wget(host) for host in hosts_list]
33
# 下面的方法将异步I/O操作放入EventLoop直到执行完毕
34
loop.run_until_complete(asyncio.wait(tasks))
35
loop.close()
36
37