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.
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 likeloop.run_until_complete(asyncio.gather(*tasks))asyncio.gatherfunction out of the context manager foraiohttpsession