我的python脚本包含以下代码:
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())
此脚本可以正常运行,但是在执行过程中会引发以下错误:
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
如何正确捕获异常以处理错误或解决错误?
谢谢。