Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"got Future <Future pending> attached to a different loop" error while using websocket.send(msg) in a while

I'm using websocket to send and receive messages in python. I've used "websocket.send(msg)" to send messages in these forms:

await ws.send(message)

and

asyncio.run(ws.send(message))

inside a while loop in which I first check whether the connection is alive and then send messages using these commands. In all of them, if number of sending times is low, there is no problem but when it increases, I get this exception for sending message

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

"Notice that RunSocket is one of my functions' name"

Then I get this error:

got Future <Future pending> attached to a different loop

Also I tried this code:

asyncio.ensure_future(await ws.send(message))

But it didn't send any messages. Can anyone help me with this error ? Any help will be appreciated.

like image 734
sina ranjkeshzadeh Avatar asked Jun 18 '26 14:06

sina ranjkeshzadeh


1 Answers

got Future attached to a different loop

When you create some async object it is attached to a current event loop (main thread has one by default). The async object is expected to be worked with while the same event loop is current. asyncio.run creates new event loop and set it is a current. Result is - you've attached async object to one event loop, but trying to use it with another one. This where error comes from.

To avoid it, you should create async object after new event loop is created by asyncio.run:

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

asyncio.run(main())
like image 124
Mikhail Gerasimov Avatar answered Jun 20 '26 05:06

Mikhail Gerasimov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!