[英]Suppress numpy exception message
除了读取.npz
数组外,我有一些代码用 try 包装
它可以产生如下异常:
Exception ignored in: <bound method NpzFile.__del__ of <numpy.lib.npyio.NpzFile object at 0x12dd65cf8>>
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/numpy/lib/npyio.py", line 226, in __del__
self.close()
File "/usr/local/lib/python3.6/site-packages/numpy/lib/npyio.py", line 217, in close
if self.zip is not None:
AttributeError: 'NpzFile' object has no attribute 'zip'
是否可以抑制此消息?
代码如下:
video_dir_list = get_video_dir_list(input_dir)
for video_dir in tqdm(video_dir_list):
try:
img_filepath_list = get_filepaths_by_extension(video_dir, ['*.jpg'])
for img_filepath in img_filepath_list:
data = load_npz_files(img_filepath)
except Exception as e:
BROKEN_VIDEO_LIST.append(video_dir)
如果只想被动处理异常,再添加一个except子句——except except AttributeError: #handle this attribute error
另外,这个异常和被忽略的异常之间有关系吗?
当我想测试给定文件是否为 npz 时,我遇到了同样的问题。 由于在关闭文件时抛出错误,因此打开文件时您不会捕获它。 您可以尝试关闭 try-except 块中的 npz 文件。 如果您想使用数据,请不要忘记在关闭之前读出数据。
def careful_loadz(path):
data = None
try:
npz = np.load(path)
data = [npz[f] for f in npz.files]
npz.close()
except (ValueError, BadZipFile, AttributeError):
print(f"Error reading the input file {path}.")
return data
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.