协程和委托语法
在发布 Python 3.5+之前,asyncio
模块使用生成器模仿异步调用,因此具有与当前 Python 3.5 版本不同的语法。
Python 3.x >= 3.5
Python 3.5 引入了 async
和 await
关键字。请注意 await func()
调用周围缺少括号。
import asyncio
async def main():
print(await func())
async def func():
# Do time intensive stuff...
return "Hello, world!"
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Python 3.x < 3.5
在 Python 3.5 之前,@asyncio.coroutine
装饰器用于定义协程。表达式的收益率用于生成器委派。请注意 yield from func()
周围的括号。
import asyncio
@asyncio.coroutine
def main():
print((yield from func()))
@asyncio.coroutine
def func():
# Do time intensive stuff..
return "Hello, world!"
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Python 3.x >= 3.5
这是一个示例,显示了如何异步运行两个函数:
import asyncio
async def cor1():
print("cor1 start")
for i in range(10):
await asyncio.sleep(1.5)
print("cor1", i)
async def cor2():
print("cor2 start")
for i in range(15):
await asyncio.sleep(1)
print("cor2", i)
loop = asyncio.get_event_loop()
cors = asyncio.wait([cor1(), cor2()])
loop.run_until_complete(cors)