1

My python script contains the following code:

import asyncio
import aiohttp
from time import time


def write_img(data):
    cnt = str(time()/60/60)
    filename = f"filename-{cnt}.jpeg"
    with open(filename, 'wb') as file:
        file.write(data)


async def fetch_cont(url, session):
    async with session.get(url, allow_redirects=True) as response:
        data = await response.read()
        write_img(data)


async def main():
    url = "https://loremflickr.com/320/240"
    tasks = []

    async with aiohttp.ClientSession() as session:
        for i in range(11):
            task = asyncio.create_task(fetch_cont(url, session))
            tasks.append(task)
        await asyncio.gather(*tasks)


if __name__ == '__main__':
    asyncio.run(main())

This script works correctly, but it throws the following errors during execution:

RuntimeError: Event loop is closed
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x00000195E74BA550>
Traceback (most recent call last):
  File "C:\Users\rhan1\AppData\Local\Programs\Python\Python38\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "C:\Users\rhan1\AppData\Local\Programs\Python\Python38\lib\asyncio\proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Users\rhan1\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 715, in call_soon
    self._check_closed()
  File "C:\Users\rhan1\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 508, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

How to catch exceptions correctly to handle errors or how to fix them?

Thank you in advance.

6
  • I'm not super familiar with asyncio, but from my understanding, one has to grab the main event loop (loop = asyncio.get_event_loop()), construct your task list (which you've done), and then run these tasks in your loop with something like loop.run_until_complete(asyncio.gather(*tasks)) Commented Feb 14, 2020 at 0:31
  • with what @monica said, there is also a bug, see github.com/aio-libs/aiohttp/issues/4324 Commented Feb 14, 2020 at 0:34
  • latest issue was 23 days ago Commented Feb 14, 2020 at 0:35
  • 1
    Try to move the asyncio.gather function out of the context manager for aiohttp session Commented Feb 14, 2020 at 0:51
  • 1
    This is a known issue in aiohttp as per github.com/aio-libs/aiohttp/issues/4324. Commented Jul 28, 2020 at 4:16

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.