python - asyncio await 在协程中无法识别

标签 python python-3.x python-asyncio

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

但是,我注意到我安装的 Python 3(版本 3.5.3,安装在树莓派上)无法识别 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)上运行良好

最佳答案

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()

关于python - asyncio await 在协程中无法识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48177039/

相关文章:

arguments - 选择 2-3 个选项作为函数参数的 Pythonic 方式

Python多处理速度

python - 如何使用 asyncio 同时运行无限循环?

python - 使用 aiohttp 将数据作为文件发送

python - Neo4j:为什么我不能在 python 中通过 find_one 找到特定节点?

用于 Code128 条形码字体的 Python Code128 编码器

python-3.x - len 和 size 的区别

python - 附加到文件无法正常工作

python-3.x - Pygame 没有移动我在屏幕上绘制的矩形

django - 有没有最简单的方法来异步运行多个python请求?