Python RuntimeError:此事件循环已在运行
Posted
技术标签:
【中文标题】Python RuntimeError:此事件循环已在运行【英文标题】:Python RuntimeError: This event loop is already running 【发布时间】:2020-08-22 10:53:03 【问题描述】:这是一个非常普遍的问题,但我实际上找不到正确的答案。我有以下代码通过 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", line 525, in run_forever
raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running
我还是不明白为什么会这样。
【问题讨论】:
【参考方案1】: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()
函数不会返回 websocket;这可能是您想要纠正的疏忽:
async def connect_to_dealer():
return await websockets.connect(websocketadress)
我删除了那里的hello_message = await websocket.recv()
/ print(hello_message)
行,因为listen_for_message()
已经收到消息并打印它们。
【讨论】:
以上是关于Python RuntimeError:此事件循环已在运行的主要内容,如果未能解决你的问题,请参考以下文章
python和PyQt5中的Quamash QventLoop“RuntimeError:没有运行事件循环”错误
RuntimeError:事件循环已关闭任务被破坏但它正在等待 Discord Python
RuntimeError:线程“Dummy-1”中没有当前事件循环