asyncio await 在协程中无法识别

asyncio await not recognized in coroutine

我正在使用一个简单的 Python 脚本来让我的头脑围绕 asyncio 模块。我正在查看可以找到的文档 here

不过,我注意到我安装的Python3(版本3.5.3,安装在raspberry pi上)不识别async def,但会识别@asyncio.coroutine.因此,我的脚本已从教程代码更改为:

import asyncio
import datetime

@asyncio.coroutine
def display_date(loop):
    end_time = loop.time() + 5.0
    while True:
        print(datetime.datetime.now())
        if (loop.time() + 1.0) >= end_time:
            break
        await asyncio.sleep(1)

loop = asyncio.get_event_loop()
# Blocking call which returns when the display_date() coroutine is done
loop.run_until_complete(display_date(loop))
loop.close()

但是,我 运行 在 await asyncio.sleep(1) 遇到语法错误。这有什么理由吗??它在我的 ubuntu 机器上运行良好(有 python 3.5.1)

async defawait - 是更新的语法,仅在 Python 3.5 之后可用。如果你 Python 不认识 async def 它也不会认识 await

我很难相信某些 3.5.3 版本出于某种原因没有实现此语法。您使用旧 python 版本的可能性更高。检查它是否添加到代码中,例如:

import sys
print(sys.version)

它将显示您 运行 的 Python 版本。

顺便说一句,asyncio 是标准的 lib 模块,你根本不应该用 pip 安装它。

await 只允许在 async def 函数中使用。

@asyncio.coroutine 装饰器标记的旧式协程应使用 yield from 语法。

您有 Python 3.5.1,所以只需使用新语法,例如:

导入异步 导入日期时间

async def display_date(loop):
    end_time = loop.time() + 5.0
    while True:
        print(datetime.datetime.now())
        if (loop.time() + 1.0) >= end_time:
            break
        await asyncio.sleep(1)

loop = asyncio.get_event_loop()
# Blocking call which returns when the display_date() coroutine is done
loop.run_until_complete(display_date(loop))
loop.close()

我对好战的小东西进行了Raspbian的重新闪现。它现在似乎可以工作了。奇怪的是,图像是 2019-11-29 版本。奇怪。