我正在使用websocket在python中发送和接收消息。我使用"websocket.send(msg("以以下形式发送消息:
await ws.send(message)
和
asyncio.run(ws.send(message))
在一个 while 循环中,我首先检查连接是否处于活动状态,然后使用这些命令发送消息。在所有这些中,如果发送次数很少,则没有问题,但是当它增加时,我会收到发送消息的异常
Task <Task pending coro=<RunSocket() running at <ipython-input-1-b17eaf75a3de>:182> cb=[_run_until_complete_cb() at D:AnacondaInstallationFolderlibasynciobase_events.py:158]> got Future <Future pending> attached to a different loop
"请注意,RunSocket 是我的函数名称之一">
然后我得到这个错误:
got Future <Future pending> attached to a different loop
我也尝试了这段代码:
asyncio.ensure_future(await ws.send(message))
但它没有发送任何消息。谁能帮我解决这个错误? 任何帮助将不胜感激。
将 Future 附加到不同的循环
当你创建一些异步对象时,它会附加到当前事件循环(默认情况下主线程有一个(。 异步对象应在当前同一事件循环时使用。asyncio.run
创建新的事件循环并将其设置为当前。 结果是 - 您已将异步对象附加到一个事件循环,但尝试将其与另一个事件循环一起使用。这就是错误的来源。
为了避免这种情况,您应该在asyncio.run
创建新事件循环后创建异步对象:
async def main():
ws = ... # create object after asyncio.run is started
res = ws.send(message)
return res
asyncio.run(main())