You need to enable JavaScript to run this app. od.download()默认返回None,如何更好处理Opendatasets下载失败问题?
优惠活动
大模型
产品
解决方案
定价
更多

od.download()默认返回None,如何更好处理Opendatasets下载失败问题?

合理的错误处理方案

od.download() 默认设计就是无论是否跳过下载、是否下载完成,只要执行过程没有触发错误就返回None,下载出错时会直接抛出异常中断执行,因此通过判断返回值是否为None的逻辑完全不会生效,无法实现错误处理。更合理的方案如下:

  • 用try-except包裹下载逻辑:所有你担心的场景(链接失效、网络中断、权限不足、磁盘空间不足等),opendatasets都会抛出对应异常,直接捕获即可覆盖所有异常场景,比判断返回值可靠得多。
  • 增加下载后文件校验:就算没有抛出异常,也可能出现文件下载不完整、损坏的情况,增加压缩包完整性校验逻辑,避免后续解压、读取文件时报错。
  • 兼容文件已存在的场景:od.download()默认如果本地已存在目标文件会直接跳过下载,也会返回None,文件校验逻辑也可以兼容这种场景,避免重复下载。

修改后的示例代码

依赖安装命令:

pip3 install opendatasets

功能实现代码:

import opendatasets as od
import zipfile
import os
import shutil
from PIL import Image
import numpy as np

def iris_scans():
    zip_path = 'iris_database.zip'
    path_extract = 'iris_database/'
    try:
        # 下载逻辑,出错会直接抛出异常进入except分支
        od.download('http://www.mae.cuhk.edu.hk/~cvl/iris_database/iris_database.zip')
        
        # 校验压缩包是否存在且完整
        if not os.path.exists(zip_path):
            raise FileNotFoundError("下载的压缩包不存在")
        with zipfile.ZipFile(zip_path, 'r') as zip_ref:
            # 校验压缩包完整性,损坏会抛出BadZipFile异常
            test_result = zip_ref.testzip()
            if test_result is not None:
                raise zipfile.BadZipFile(f"压缩包损坏,损坏文件:{test_result}")
            zip_ref.extractall(path_extract)
    except Exception as e:
        print(f'Iris Scans - 下载或解压失败:{str(e)}')
        return [[]*1778]
    
    os.remove(path_extract + 'readme.txt')
    
    filenames = os.listdir(path_extract)
    scans = []
    for f in filenames:
        img = Image.open(path_extract + f)
        matrix = np.array(img)
        scans.append(matrix)
    
    shutil.rmtree(path_extract)
    os.remove(zip_path)
    
    # 数据增强部分保持不变
    scans_90 = [np.rot90(s) for s in scans]
    scans_180 = [np.rot90(s) for s in scans_90]
    scans_270 = [np.rot90(s) for s in scans_180]

    scans_flip = [np.flip(s) for s in scans]
    scans_flip_90 = [np.rot90(s) for s in scans_flip]
    scans_flip_180 = [np.rot90(s) for s in scans_flip_90]
    scans_flip_270 = [np.rot90(s) for s in scans_flip_180]

    scans += scans_90
    scans += scans_180
    scans += scans_270

    scans += scans_flip_90
    scans += scans_flip_180
    scans += scans_flip_270

    return scans

scans = iris_scans()
print(scans[0])
print(len(scans))

内容的提问来源于stack exchange,提问作者user16341274

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 22:00:01