首页 > 解决方案 > 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

标签: pythonpython-asyncio

解决方案


正如消息所说,使用

    await asyncio.sleep(2)

推荐阅读