# 協程 + 事件循環 import asyncio async def func(): # async關鍵字不能和yield一塊兒使用,引入coroutine裝飾器來裝飾downloader生成器。 print('start') # 異步調用asyncio.sleep(1): await asyncio.sleep(1) # time.sleep 異步的接口 對象 必須實現__await__ # await 就至關於 yield from print('end') # 獲取EventLoop: loop = asyncio.get_event_loop() task1 = loop.create_task(func()) task2 = loop.create_task(func()) # 執行coroutine loop.run_until_complete(asyncio.wait([task1, task2])) # loop.run_until_complete(func()) # asyncio是一個底層模塊 # 他完成了幾個任務的輪流檢測io,而且在遇到io的時候可以及時在任務之間進行切換 # 而後達到使用單線程實現異步的方式 # aiohttp # 徹底使用asyncio做爲底層模塊完成的 # loop 你的循環 # 你的協程任務就是 被async語法約束的 函數 # 你的協程任務遇到io才能切出去,如何標識你的任務遇到io了呢? await 對象 # async 語法 幫助咱們建立協程任務 # asyncio模塊 : 異步io模塊 對協程任務的循環管理 內置了不少異步的接口幫助咱們 異步的socketserver,採用異步的形式去訪問socket server
import asyncio async def get_url(): reader,writer = await asyncio.open_connection('www.shuoiliu.com',80) writer.write(b'GET / HTTP/1.1\r\nHOST:www.shuoiliu.com\r\nConnection:close\r\n\r\n') all_lines = [] async for line in reader: data = line.decode() all_lines.append(data) html = '\n'.join(all_lines) return html async def main(): tasks = [] for url in range(2): tasks.append(asyncio.ensure_future(get_url())) for res in asyncio.as_completed(tasks): result = await res print(result) if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) # 處理一個任務 loop.run_until_complete(asyncio.wait([main()])) # 處理多個任務 task = loop.create_task(main()) # 使用create_task獲取返回值 loop.run_until_complete(task) loop.run_until_complete(asyncio.wait([task]))
import asyncio # 執行任務獲取返回值 ''' async def hello(): print("Hello world!") await asyncio.sleep(1) print("Hello again!") return 'done' loop = asyncio.get_event_loop() task = loop.create_task(hello()) loop.run_until_complete(task) ret = task.result() print(ret) ''' # 執行多個任務按照返回的順序獲取返回值 import asyncio async def hello(i): print("Hello world!",i) await asyncio.sleep(i) print("Hello again!") return 'done', i async def main(): tasks = [] for i in range(5): tasks.append(asyncio.ensure_future(hello((20 - i) / 10))) for res in asyncio.as_completed(tasks): result = await res print(result) loop = asyncio.get_event_loop() loop.run_until_complete(main())