【发布时间】:2021-07-20 08:31:45
【问题描述】:
更新:原来od.download() 按设计返回None。
有什么比None 检查od.download()“失败”更好?
我正在使用opendatasets lib 下载.zip 文件。
在iris_scans();行print(download),没有if-statement 打印None。
但是,在调用scans = iris_scans() 时返回数据,后续打印可以成功显示数据。
if-statement 的目的是“优雅的错误处理”。
注意:我使用了if-statement 而不是try-except,因为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():
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))
【问题讨论】:
-
查看source on Github,该函数没有返回任何内容,因此它始终为None。我认为您必须使用 try/except 语句。
-
奇怪的是它的设计...有什么可以替代
if download == None,而不是try-except?在这种情况下,我需要有很多行,每行都涵盖所有可能的错误名称。 -
或者,为了制作
try-excepts,Github 资源是否在任何地方列出了所有错误名称?我找不到他们。 -
查看我链接的文件的第 58 行和第 71 行,它可以引发
urllib.error.URLError、IOError或RuntimeError。 -
@Henry 参考我的解决方案。
标签: python-3.x nonetype