Python 3.5 增加了對async def and await的支持,同樣的異步代碼看起來干凈了很多,也更易讀。
import aiohttp import asyncio async def get_status(url, id): r = await aiohttp.get(url) print(r.status, id) r.close() tasks = [] for i in range(100): tasks.append(asyncio.ensure_future(get_status('https://api.github.com/events', id=i))) if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait(tasks)) loop.close()