Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with event_loops in Python 3.10

I try to get data from the Binance Websocket. With python 3.9 as Interpreter it runs fine, but with 3.10 it gives me errors :(

Here is the code:

import asyncio
from binance import AsyncClient, BinanceSocketManager


async def main():
    client = await AsyncClient.create()
    bm = BinanceSocketManager(client)
    # start any sockets here, i.e a trade socket
    ts = bm.trade_socket('BNBBTC')
    # then start receiving messages
    async with ts as tscm:
        while True:
            res = await tscm.recv()
            print(res)


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

I get this error:

DeprecationWarning: There is no current event loop
  loop = asyncio.get_event_loop()

I use PyCharm as IDE.

Anyone there who can help me, please?

like image 464
Max Power Avatar asked Jun 17 '26 11:06

Max Power


2 Answers

This is a deprecation warning, that means the behaviour of the function get_event_loop() you called will soon change, in that it will no longer create a new event loop, but rather raise RuntimeError like get_running_loop. From the looks of it the intended way is to create a new event loop explicitly rather than implicitly.

if __name__ == "__main__":
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(main())

I am not sure if asyncio.set_event_loop(loop) is actually necessary.

like image 66
Jan Christoph Terasa Avatar answered Jun 20 '26 01:06

Jan Christoph Terasa


The recommended api for running even loop is asyncio.run (introduced in Python 3.7).

The example can be modified to adopt it:


if __name__ == "__main__":
    asyncio.run(main())
like image 24
Andrew Svetlov Avatar answered Jun 20 '26 01:06

Andrew Svetlov