python - python-asyncio/aiohttp:RuntimeError“事件循环已关闭”
问题描述
我的 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
如何正确捕获异常以处理错误或如何修复它们?
先感谢您。
解决方案
推荐阅读
- c# - Main() 方法仅在请求进来时执行
- php - Laravel 图像验证仅接受 .png 文件
- javascript - 更新嵌套数组
- flutter - 如何使设备后退按钮转到flutter webview中的上一页
- javascript - 电子示例不适用于“退出信号 SIGSEGV”
- python - 如何设置 Seaborn 散点图色调等于特征而不是单个特征的值?
- matlab - 安装 matlab 意外错误“C:\Program Files (x86)\MATLAB\R2015b 的任务 MATLAB R2015b 启动加速器不存在”
- postgresql - 我对 postgreSQL 有疑问;无法恢复转储的数据库
- html - CSS制作一个通常向右浮动的元素,当视口太小时转到新行
- python - 试图通过 Pandas df 循环寻找 PU 字符串,我希望从这里记录行号