1.併發執行任務示例:html
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.併發爬取網頁內容示例:異步
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()
執行結果:async
3.異步協程詳細介紹:ide
https://www.cnblogs.com/zhaof/p/8490045.html函數