简体   繁体   English

抑制 numpy 异常消息

[英]Suppress numpy exception message

I have some code wrapped with try except that read .npz arrays除了读取.npz数组外,我有一些代码用 try 包装

It can produce exceptions like:它可以产生如下异常:

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'

Is it possible to suppress this message?是否可以抑制此消息?

Code looks like:代码如下:

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)

If you just want to passively handle an exception, add another except clause-- except AttributeError: #handle this attribute error如果只想被动处理异常,再添加一个except子句——except except AttributeError: #handle this attribute error

Also, is there a relationship between this exception, and the ignored one?另外,这个异常和被忽略的异常之间有关系吗?

I encountered your same problem when I wanted to test if a given file was npz.当我想测试给定文件是否为 npz 时,我遇到了同样的问题。 Since the error is thrown when the file is closed, you will not catch it when opening the file.由于在关闭文件时抛出错误,因此打开文件时您不会捕获它。 You can try closing the npz file within the try-except block.您可以尝试关闭 try-except 块中的 npz 文件。 Don't forget to read out the data before closing if you would like to use the data.如果您想使用数据,请不要忘记在关闭之前读出数据。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM