使用 websocket.send(msg) 一段时间时出现“将 Future <Futureending> 附加到不同的循环”错误

sin*_*deh 5 python runtime-error websocket async-await python-asyncio

我正在使用 websocket 在 python 中发送和接收消息。我使用“websocket.send(msg)”以这些形式发送消息:

await ws.send(message)
Run Code Online (Sandbox Code Playgroud)

asyncio.run(ws.send(message))
Run Code Online (Sandbox Code Playgroud)

在 while 循环中,我首先检查连接是否处于活动状态,然后使用这些命令发送消息。在所有这些中,如果发送次数较少,没有问题,但是当发送次数增加时,我会收到发送消息的异常

Task <Task pending coro=<RunSocket() running at <ipython-input-1-b17eaf75a3de>:182> cb=[_run_until_complete_cb() at D:\Anaconda\InstallationFolder\lib\asyncio\base_events.py:158]> got Future <Future pending> attached to a different loop
Run Code Online (Sandbox Code Playgroud)

“请注意,RunSocket 是我的函数名称之一”

然后我得到这个错误:

got Future <Future pending> attached to a different loop
Run Code Online (Sandbox Code Playgroud)

我也尝试过这段代码:

asyncio.ensure_future(await ws.send(message))
Run Code Online (Sandbox Code Playgroud)

但它没有发送任何消息。谁能帮我解决这个错误?任何帮助将不胜感激。

Mik*_*mov 9

将 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())
Run Code Online (Sandbox Code Playgroud)