od.download() == None 但它不是空的 |异常处理 Opendatasets

od.download() == None but it's not empty | Exception handling Opendatasets

更新:结果是 od.download() returns None 设计。

什么可能比 None 检查 od.download() “失败”?


我正在使用 opendatasets 库下载 .zip 文件。

iris_scans();第 print(download) 行,没有 if-statement 打印 None.

但是,在调用时scans = iris_scans()返回数据,后续打印可以成功显示数据。


if-statement 的目的是为了“优雅的错误处理”。

注意:我使用了 if-statement 而不是 try-except 因为 download == None 有很多可能性(例如死 link, 连接中断等)


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

def iris_scans():
  download = od.download('http://www.mae.cuhk.edu.hk/~cvl/iris_database/iris_database.zip')
  """
  if download == None:
    print('Iris Scans - Link could not be established')
    return [[]*1778]
  """
  print(download)

  path_extract = 'iris_database/'
  with zipfile.ZipFile('iris_database.zip', 'r') as zip_ref:
    zip_ref.extractall(path_extract)
  
  os.remove(path_extract + 'readme.txt')
  
  filenames = os.listdir(path_extract)
  scans = []
  for f in filenames:
    img = Image.open(path_extract + f)
    #print("IMG", img)
    matrix = np.array(img)
    #print("MATRIX", matrix)
    scans.append(matrix)
  
  shutil.rmtree(path_extract)
  os.remove(path_extract[:-1] + '.zip')
  
  # Data Augmentation
  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))

最初的问题是为下载实施某种形式的异常处理的道路上的障碍。

od.download() == None 设计;因此需要替代 if download == None

正如@Henry 所指出和协助的那样;下面的 Try-except 合并了 Github source.

中发现的所有异常
...
import urllib

def iris_scans():
  try:
    download = od.download('http://www.dgcdgyugcwyugyugcasc.com/wqduiuwqdwq') # BROKEN
    ...

    return scans
  
  except (urllib.error.URLError, IOError, RuntimeError) as e:
    print('Iris Scans - failed')
    return [[]*1778]
Iris Scans - failed
[]
1

对此 post 的最佳答案在一行中演示了许多例外情况。