用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!")