我正在使用一个简单的Python脚本来理解asyncio模块。我正在浏览可以在here上找到的文档
然而,我注意到我安装的Python3(版本3.5.3,安装在覆盆子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)上运行得很好。
发布于 2018-01-10 21:51:16
我在这个好战的小东西上重新闪现了一次Raspbian。它现在似乎起作用了。奇怪的是,图片是2019-11-29版本。真奇怪。
发布于 2018-01-10 20:21:03
仅允许在async def函数内使用await。
由@asyncio.coroutine装饰器标记的旧式协程应该使用yield from语法。
您使用的是Python 3.5.1,因此只需使用新的语法,例如:
导入asyncio导入日期时间
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()发布于 2018-01-10 13:25:31
async def和await -是从Python3.5开始才能使用的新语法。如果Python不能识别async def,那么它也不能识别await。
我很难相信一些3.5.3版本由于某种原因没有实现这种语法。更有可能的是,您使用的是较旧的python版本。检查它,添加到代码中,例如:
import sys
print(sys.version)它将显示您正在运行的Python版本。
顺便说一句,asyncio是标准库模块,你根本不应该用pip安装它。
https://stackoverflow.com/questions/48177039
复制相似问题