2
import asyncio import aiohttp aut_token = ("token") tasks = [] iter_flag = True interval = 0 seq = 0 class WAPI: async def receiver(WAPI_S): async for msg in WAPI_S: global interval global seq data = msg.json() seq = data.get("s") if data.get("op") == 10: interval = data.get("d").get("heartbeat_interval") / 1000 if data.get("op") == 11: pass raise aiohttp.ClientError async def heartbeating(WAPI_S): while iter_flag: await WAPI_S.send_json({ "op": 1, "d": seq }) await asyncio.sleep(interval) async def event_manager(): loop = asyncio.get_running_loop() try: async with aiohttp.ClientSession() as session: async with session.ws_connect("url") as WAPI_S: task_receive = loop.create_task(WAPI.receiver(WAPI_S)); task_heartbeating = loop.create_task(WAPI.heartbeating(WAPI_S)) tasks.append(task_receive); tasks.append(task_heartbeating) await asyncio.gather(*tasks) except aiohttp.ClientError: global iter_flag iter_flag = False await asyncio.sleep(interval) for task in tasks: task.cancel() try: loop.close() except: loop.stop() asyncio.run(WAPI.event_manager()) 

I am trying to implement catching ClientError exception with loop closing, however, loop.close throws "RuntimeError: Event loop stopped before Future completed."

How to implement interception correctly?

1 Answer 1

2

You do not need to keep track of your tasks manually, you can simply use

asyncio.all_tasks():

Return a set of not yet finished Task objects run by the loop.

And then a:

pending = asyncio.all_tasks() c in pending: wait_for(c, timeout=5) 

Also, you are trying to stop the loop while you are in it. This is the pattern I use most of the times:

async def main(): <do some stuff> loop = asyncio.get_event_loop() try: loop.run_until_complete(main()) except ExceptionYouWantToHandle: <cleaning up> finally: loop.stop() 

And in the event_manager you simply return once you get an execption or you pass the exception

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.