在处理来自包/模块的错误时如何处理Python异常

在处理来自包/模块的错误时如何处理Python异常,python,python-3.x,exception,exception-handling,Python,Python 3.x,Exception,Exception Handling,我正在使用一个名为WCS.all_world2pix的astropy软件包,以便将许多度坐标转换为图像上的像素坐标。在许多坐标对上运行时,我最终遇到了一个错误,使我的程序无法运行。以下是导致错误的代码,以及错误本身: import glob import numpy as np import re from astropy.io import fits from astropy.wcs import WCS initial_data, centroid_coords = [], [] imag

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

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.

如何处理此异常?我以前从未实际处理过这些问题,因此非常感谢您的帮助。谢谢

回溯会告诉您异常类型,因此您可以使用它:

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

你现在所拥有的看起来会有用的。不过,我想为您推荐两个小的编辑:

  • try
    块中包含尽可能少的行数,这样就不会掩盖意外的错误情况
  • 再次捕获特定错误,这样您就不会掩盖意外情况(
    除非
    本身会捕获每个错误)


你的打印报表在这里具体做什么?这对我不起作用,我不熟悉字符串前面的语法
{ex!r}
,以及
f
starts@curious_cosmo对于第一个问题:
f'{spam}和{eggs}'
是编写
{spam}和{eggs}的简写方法。格式(spam=spam,eggs=eggs)
在Python 3.6中添加。有关详细信息,请参阅
{ex!r}
是正常的,可以追溯到2.6/3.0;
!r
意味着打印
repr
,而不是
str
(这通常对调试更有用,尤其是在打印异常时)。好奇的cosmo可能有一些教程(也许还有一些答案)比我链接到的官方文档更好地解释了这两件事,如果您需要知道的内容比我介绍的内容多,但比那些密集的参考文档要少。@quentious_cosmo但与此同时,
print
只是一个示例,如果您需要一些关于哪些文件被跳过以及为什么被跳过的反馈,您可以打印出来。你可以把任何你想要的东西放在那里,或者什么都不放;你不必只是复制粘贴你看到的每一行代码。谢谢——我不只是复制粘贴它,希望它能工作;我只是想看看它会输出什么,但是在print语句中出现了一个错误,这就是我问的原因。我确实想出了我自己的打印声明放在那里,我原来的问题已经解决了。
except astropy.WcsError as ex:
    print(f'file {f} raised {ex!r}, skipping')
    continue
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)))    
from astropy.wcs.wcs import NoConvergence