Python RuntimeError:此事件循环已在运行

问题描述

这是一个非常普遍的问题,但是我实际上找不到正确的答案。我有以下代码通过websocket连接到服务器,我希望它保持活动状态并继续监听它发送的消息,如下所示:

import asyncio
import websockets
import nest_asyncio
nest_asyncio.apply()
            
async def listen_for_message(websocket):
    while True:
        await asyncio.sleep(0)
        message = await websocket.recv()
        print(message)

async def connect_to_dealer():
    websocket = await websockets.connect(websocketadress)

    hello_message = await websocket.recv()
    print(hello_message)

async def my_app():
    websocket = await connect_to_dealer()
    asyncio.ensure_future(listen_for_message(websocket))

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(my_app())
    loop.run_forever()

它会引发错误

  File "\untitled0.py",line 71,in <module>
    loop.run_forever()
  File "\Anaconda3\lib\asyncio\base_events.py",line 525,in run_forever
    raise RuntimeError('This event loop is already running') 
RuntimeError: This event loop is already running

并且没有

import nest_asyncio
nest_asyncio.apply()

我得到:

  File "\untitled0.py",line 70,in <module>
    loop.run_until_complete(my_app()) 
  File "\Anaconda3\lib\asyncio\base_events.py",line 570,in run_until_complete
    self.run_forever()
  File "\Anaconda3\lib\asyncio\base_events.py",in run_forever
    raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running

我仍然不明白为什么这样做。

解决方法

loop.run_until_complete()已经“永远”运行了循环。

与其等待您的listen_for_message(),而是等待它。那将永远运行,因为listen_for_message()本身永远不会返回:

async def my_app():
    websocket = await connect_to_dealer()
    await listen_for_message(websocket)

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(my_app())

请注意,您的connect_to_dealer()函数不会返回网络套接字;这可能是您要纠正的疏忽:

async def connect_to_dealer():
    return await websockets.connect(websocketadress)

我在此处删除了hello_message = await websocket.recv() / print(hello_message)行,因为listen_for_message()已经收到消息并打印了。