Python 警告系统#

Astropy用 Python warnings 发出警告消息的模块。使用warnings模块的详细信息对于Python是通用的,并且适用于使用该系统的任何Python软件。用户可以使用python命令行参数来抑制警告 -W"ignore" 启动交互式python会话时。例如::

$ python -W"ignore"

用户还可以在运行python脚本时使用命令行参数,如下所示:

$ python -W"ignore" myscript.py

也可以在python脚本中禁止警告。例如,从对 astropy.io.fits.writeto 函数可以在Python脚本中使用 warnings.filterwarnings 功能如下:

>>> import warnings
>>> from astropy.io import fits
>>> warnings.filterwarnings('ignore', category=UserWarning, append=True)
>>> fits.writeto(filename, data, overwrite=True)

在简单调用的警告筛选器规范列表中插入条目的等效方法 warnings.simplefilter ::

>>> warnings.simplefilter('ignore', UserWarning)

Astropy有自己的警告等级, AstropyWarningAstropyUserWarning . 所有来自Astropy的警告都是基于这些警告级别的(参见下面的区别)。因此,您可以忽略来自Astropy的所有警告(同时仍然允许通过其他库(如Numpy)发出的警告,方法如下:

>>> from astropy.utils.exceptions import AstropyWarning
>>> warnings.simplefilter('ignore', category=AstropyWarning)

警告过滤器也可以在特定上下文中使用 warnings.catch_warnings 上下文管理器:

>>> with warnings.catch_warnings():
...     warnings.simplefilter('ignore', AstropyWarning)
...     fits.writeto(filename, data, overwrite=True)

如上所述,实际上 two Astropy警告的基类。主要区别是 AstropyUserWarning 用于警告 预定的 对于典型用户(例如“警告:不明确的单位”,可能是由于输入不正确造成的)。相反, AstropyWarning 警告是 not AstropyUserWarning 可能是针对较低级别的警告,对于编写 uses Astropy(例如,下面讨论的弃用警告)。因此,如果你是一个只想让一切安静下来的用户,上面的代码就足够了,但是如果你是一个开发人员,想对你的用户隐藏与开发相关的警告,你可能还是希望允许通过 AstropyUserWarning .

Astropy还会在使用不推荐的API特性时发出警告。如果你愿意的话 安静 弃用警告,可以使用 -Wi::Deprecation . 这会将所有不推荐警告设置为忽略。还有一个特殊的 AstropyDeprecationWarning 它只能用于禁用来自Astropy的弃用警告。

the CPython documentation 有关-W参数的详细信息。