gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:34:51 35 4
gpt4 key购买 nike

我正在使用一个简单的 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/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com