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

时间:2018-08-24 00:54:36

标签: python python-3.x exception exception-handling

我正在使用一个名为astropy的{​​{1}}包,以便将度数的许多坐标转换为图像上的像素坐标。在多对坐标上运行该程序时,最终遇到了一个错误,该错误使程序无法运行。这是导致错误的代码,以及错误本身:

WCS.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)))

我只想跳过那些导致此错误的图像。但是我不确定如何将其作为异常处理,因为它不是通常的Type / Value / SyntaxError等。

当它遍历我的循环时,如果/如果发生此错误,我希望它继续循环中的下一个元素,而不会为导致错误的元素添加任何内容。我想到的是这样的东西:

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.

如何处理此异常?我以前从未真正处理过这些内容,因此可以提供任何帮助。谢谢!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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