处理包/模块中的错误时如何处理Python异常

问题描述 投票:1回答:2

我正在使用一个名为astropyWCS.all_world2pix包,以便将许多度数坐标转换为图像上的像素坐标。在多对坐标上运行时,我最终遇到了一个错误,导致程序停止运行。以下是导致错误的代码和错误本身:

import glob
import numpy as np
import re
from astropy.io import fits
from astropy.wcs import WCS

initial_data, centroid_coords = [], []
image_files = glob.glob('/home/username/Desktop/myfolder/*.fits')

for image in image_files:
    img_data = np.nan_to_num(fits.getdata(image))

    obj_num = int(re.search('2\d{6}', image).group(0))
    count_num = int(re.search('_(\d+)_', image).group(1))
    obj_index = int(np.where(good_data == obj_num)[0])
    count_index = int(np.where(np.array(all_counters[obj_index]) == count_num)[0])

    ra, dec = pos_match[obj_index][count_index]
    w = WCS(image)
    x, y = w.all_world2pix(ra, dec, 0)
    initial_data.append(img_data)
    centroid_coords.append((float(x), float(y)))

错误:

x, y = w.all_world2pix(ra, dec, 0)  
  File "/usr/local/anaconda3/lib/python3.6/site-packages/astropy/wcs/wcs.py", line 1827, in all_world2pix
    'input', *args, **kwargs
  File "/usr/local/anaconda3/lib/python3.6/site-packages/astropy/wcs/wcs.py", line 1269, in _array_converter
    return _return_list_of_arrays(axes, origin)
  File "/usr/local/anaconda3/lib/python3.6/site-packages/astropy/wcs/wcs.py", line 1225, in _return_list_of_arrays
    output = func(xy, origin)
  File "/usr/local/anaconda3/lib/python3.6/site-packages/astropy/wcs/wcs.py", line 1826, in <lambda>
    quiet=quiet),
  File "/usr/local/anaconda3/lib/python3.6/site-packages/astropy/wcs/wcs.py", line 1812, in _all_world2pix
    slow_conv=ind, divergent=inddiv)
astropy.wcs.wcs.NoConvergence: 'WCS.all_world2pix' failed to converge to the requested accuracy.
After 2 iterations, the solution is diverging at least for one input point.

我希望能够跳过那些导致此错误的图像。但我不确定如何处理这个异常,因为它不是通常的Type / Value / SyntaxError等...

因为它正在通过我的循环,当/如果发生这个错误我只是喜欢它继续循环中的下一个元素而不会为导致错误的那个附加任何东西。这样的事情就是我想到的:

for image in image_files:
    img_data = np.nan_to_num(fits.getdata(image))
    obj_num = int(re.search('2\d{6}', image).group(0))
    count_num = int(re.search('_(\d+)_', image).group(1))
    obj_index = int(np.where(good_data == obj_num)[0])
    count_index = int(np.where(np.array(all_counters[obj_index]) == count_num)[0])

    ra, dec = pos_match[obj_index][count_index]
    w = WCS(image)
    try:
        x, y = w.all_world2pix(ra, dec, 0)
        initial_data.append(img_data)
        centroid_coords.append((float(x), float(y)))    
    except: # skip images where coordinates fail to converge
        # Not sure how to identify the error here
        continue

我该如何处理这个异常?我以前从未真正处理过这些,所以任何帮助都会受到赞赏。谢谢!

python python-3.x exception exception-handling
2个回答
1
投票

你现在拥有的东西看起来像是有效的。我想为您推荐两个小编辑:

  • 包括尽可能少的try块中的行数,因此您不会屏蔽意外的错误情况
  • 捕获特定错误,再次,以便您不掩盖意外情况(except本身将捕获每个错误)

for image in image_files:
    < the code you already have, up to the `try` block >

    try:
        x, y = w.all_world2pix(ra, dec, 0)
    except NoConvergence:
        continue

    initial_data.append(img_data)
    centroid_coords.append((float(x), float(y)))    

请注意,您可能还需要在脚本顶部为NoConvergence错误添加导入:

from astropy.wcs.wcs import NoConvergence

0
投票

回溯告诉你异常类型,所以你可以使用它:

except astropy.wcs.wcs.NoConvergence as ex:
    print(f'file {f} raised {ex!r}, skipping')
    continue

当然,您可能必须导入一些额外的子包或模块才能访问该异常类型。

但是,您真正想要做的是检查文档。大多数精心设计的软件包都会为您提供一个您应该看到的异常列表,并且通常会有一些您可以捕获的易于访问的超类,而更详细的异常可能是私有的并且可能会发生变化,或者可能是公开的但很少需要。

例如,也许有像astropy.WcsError这样的东西,一大堆私有异常类型都是它们的子类,包括你所看到的NoConvergence。如果您在文档中看到类似的内容,那就是您应该处理的内容:

except astropy.WcsError as ex:
    print(f'file {f} raised {ex!r}, skipping')
    continue
© www.soinside.com 2019 - 2024. All rights reserved.