協程和委託語法

在釋出 Python 3.5+之前,asyncio 模組使用生成器模仿非同步呼叫,因此具有與當前 Python 3.5 版本不同的語法。

Python 3.x >= 3.5

Python 3.5 引入了 asyncawait 關鍵字。請注意 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)