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