1.并发执行任务示例:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 import asyncio, time 2 3 #异步协程 4 async def hello(): 5 """ 6 这边程序运行时,线程不会等待这个sleep 1s,将直接终端继续执行往下执行,这边5个任务会并发执行 7 :return: 8 """ 9 print("hello world") 10 asyncio.sleep(1) 11 print("Hello again! time:{}".format(time.time())) 12 13 def run(): 14 for i in range(5): 15 loop.run_until_complete(hello()) 16 17 if __name__ == "__main__": 18 loop = asyncio.get_event_loop() 19 run() 20 loop.close()
执行结果:
2.并发爬取网页内容示例:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #通过asyncio 协程实现并发获取网站数据 2 #await语法相当于 yield from 3 import asyncio 4 5 async def wget(host): 6 print("wget {}...".format(host)) 7 connect = asyncio.open_connection(host, 80) 8 reader, writer = await connect 9 header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host 10 writer.write(header.encode('utf-8')) 11 await writer.drain() 12 result = "" 13 while True: 14 line = await reader.readline() 15 if not line: 16 break 17 result +='%s header > %s\n' % (host, line.decode('utf-8').rstrip()) 18 writer.close() 19 return result 20 21 loop = asyncio.get_event_loop() 22 tasks = [asyncio.ensure_future(wget(host)) for host in ['ncm.itsmsit.cnsuning.com', 'emm.cloudytrace.com']] 23 loop.run_until_complete(asyncio.wait(tasks)) 24 for index, task in enumerate(tasks): 25 #获取任务执行的结果也就是wget()函数return的值 26 print("结果{}:".format(index)) 27 print(task.result()) 28 loop.close()
执行结果:
3.异步协程详细介绍:
https://www.cnblogs.com/zhaof/p/8490045.html