python - asyncio 2 工作人员 RuntimeWarning:从未等待协程“睡眠”
问题描述
我正在尝试学习 asyncio,非常感谢任何提示。我正在为如何创建 2 个轮流打印消息的进程而苦苦挣扎。
import asyncio
async def firstWorker():
print(f'asyncio message worker 1 Hello!')
asyncio.sleep(2)
async def secondWorker():
print(f'asyncio message worker 2 Hello!')
asyncio.sleep(2)
# Running the ven_client in the Python AsyncIO Event Loop
loop = asyncio.get_event_loop()
try:
asyncio.ensure_future(firstWorker())
asyncio.ensure_future(secondWorker())
loop.run_forever()
except KeyboardInterrupt:
pass
finally:
print("Closing Loop")
loop.close()
这将引发错误,并且不会继续运行:
asyncio message worker 1 Hello!
Warning (from warnings module):
File "basic.py", line 6
asyncio.sleep(2)
RuntimeWarning: coroutine 'sleep' was never awaited
asyncio message worker 2 Hello!
Warning (from warnings module):
File "basic.py", line 11
asyncio.sleep(2)
RuntimeWarning: coroutine 'sleep' was never awaited
解决方案
正如消息所说,使用
await asyncio.sleep(2)
推荐阅读
- android - Andorid 如何在 Documents 数组中添加值
- c# - 使用 Cropper.js 和 Asp.net 裁剪图像
- python-3.x - 使用 apply/lambda 将分组数据帧转换为字典
- javascript - 未找到 Webpack 和 React 图像
- docker - Docker 服务仅对本地主机可用
- python - 从列表 Python 错误中打印 __init__ 对象
- angular - Angular,奇怪的错误(未知 url)的 Http 失败响应:0 Unknown Error using APP_INITIALIZER
- doctrine - (教义)选择数组集合不为空的地方?
- python - Pandas 数据框条件替换和按列修剪
- google-home - 有没有办法创建一个“Action on Google”来回答“Google play X radio”并实际播放流?