用asyncio
提供的@asyncio.coroutine
能夠把一個generator標記爲coroutine類型,而後在coroutine內部用yield from
調用另外一個coroutine實現異步操做。異步
爲了簡化並更好地標識異步IO,從Python 3.5開始引入了新的語法async
和await
,能夠讓coroutine的代碼更簡潔易讀。async
請注意,async
和await
是針對coroutine的新語法,要使用新的語法,只須要作兩步簡單的替換:spa
@asyncio.coroutine
替換爲async
;yield from
替換爲await
。@asyncio.coroutine def hello(): print("Hello world!") r = yield from asyncio.sleep(1) print("Hello again!")
用新語法從新編寫以下:code
async def hello(): print("Hello world!") r = await asyncio.sleep(1) print("Hello again!")