Python,禁用警告过滤器

Python, disable warnings filter

如何禁用警告过滤?

我想多次输出相同的警告,但是库中的过滤器避免多次输出相同的警告。

import warnings

for i in range(2):
    warnings.warn("warning message")

输出:

C:\Users\me\my_script.py:4: UserWarning: warning message
  warnings.warn("warning message")

文档在这里: https://docs.python.org/2/library/warnings.html

显然我必须在过滤器入口处的元组中设置 "always",我不知道该怎么做,也不知道从哪里访问这个元组。

您可以使用 warnings.simplefilter() and warnings.filterwarnings() functions 更新警告过滤器;来自模块介绍:

The determination whether to issue a warning message is controlled by the warning filter, which is a sequence of matching rules and actions. Rules can be added to the filter by calling filterwarnings() and reset to its default state by calling resetwarnings().

要使所有警告在第一个问题之后重复出现,请使用

warnings.simplefilter('always')

您可以通过添加更多要过滤的详细信息来对此进行扩展。例如,您的 warnings.warn() 调用未指定类别,因此默认使用 warnings.UserWarning;您可以将其添加到过滤器中:

warnings.simplefilter('always', warnings.UserWarning)

等如果您只想指定一些过滤器参数,您也可以使用关键字参数,例如 append=True.

使用 python 2.7.15rc1,为了禁用所有警告,我使用了这两行代码:

import warnings
warnings.simplefilter("ignore")

希望有用