task 是协程和 Future 的桥梁。
# coding=utf-8
import asyncio
import time
# 协程中是不能使用同步阻塞编程的
async def get_html (url):
print('start get url', url)
await asyncio.sleep(2)
print('end get url')
async def get_html2 (url):
print('start get url', url)
await asyncio.sleep(4)
print('end get url')
if __name__ == '__main__':
start_time = time.time()
loop = asyncio.get_event_loop()
t1 = [get_html('www.baidu.com') for i in range(10)]
t2 = [get_html2('www.google.com') for i in range(10)]
try:
# loop.run_until_complete(asyncio.wait(t1 + t2))
loop.run_until_complete(asyncio.gather(*t1, *t2))
except KeyboardInterrupt:
for task in asyncio.Task.all_tasks():
print(task.cancel())
loop.stop()
print('times', time.time() - start_time)
输出:
start get url www.baidu.com
start get url www.baidu.com
start get url www.baidu.com
start get url www.baidu.com
start get url www.baidu.com
start get url www.baidu.com
start get url www.baidu.com
start get url www.baidu.com
start get url www.baidu.com
start get url www.baidu.com
start get url www.google.com
start get url www.google.com
start get url www.google.com
start get url www.google.com
start get url www.google.com
start get url www.google.com
start get url www.google.com
start get url www.google.com
start get url www.google.com
start get url www.google.com
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
end get url
times 4.003652095794678