【问题标题】:"got Future <Future pending> attached to a different loop" error while using websocket.send(msg) in a while在一段时间内使用 websocket.send(msg) 时出现“将 Future <Future pending> 附加到不同的循环”错误
【发布时间】:2020-05-20 19:29:21
【问题描述】:

我正在使用 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:\Anaconda\InstallationFolder\lib\asyncio\base_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))

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

【问题讨论】:

    标签: python websocket async-await runtime-error python-asyncio


    【解决方案1】:

    将 Future 附加到不同的循环

    当您创建一些异步对象时,它会附加到current 事件循环(主线程默认有一个)。 在同一事件循环处于当前状态时,预计将使用异步对象。 asyncio.run 创建新的事件循环并将其设置为当前。 结果是 - 您已将异步对象附加到一个事件循环,但试图将其与另一个事件循环一起使用。这就是错误的来源。

    为避免这种情况,您应该在asyncio.run 创建新的事件循环后创建异步对象:

    async def main():
        ws = ...  # create object after asyncio.run is started
        res = ws.send(message)
        return res
    
    asyncio.run(main())
    

    【讨论】:

    • 感谢您的回答,但我不明白为什么它工作了大约 2 分钟没有任何问题,然后出现此错误。
    • @sinaranjkeshzade 如果没有可重现的代码,很难准确地说出来,但可能是提到的异步对象是在 ws 内部创建的,并且没有立即使用,因此发生错误需要时间。
    • “创建一些异步对象”指的是:用async def coro()定义一个协程还是用coro()调用它?是否可以改变这一点,例如在不同线程内的不同事件循环中执行协程?
    • @JeanMonet 它指的是调用异步函数 - coro()。一旦调用协程函数,就会创建异步对象(或协程对象)并将其附加到事件循环。如果你想在不同的事件循环中等待某些东西,你应该在不同的事件循环设置为默认值时调用coro()。有关示例,请参见此答案 - stackoverflow.com/a/52301233/1113207
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-19
    相关资源
    最近更新 更多