启用 Python 中的所有警告,在它们被导入的模块禁用后

Enable all warnings in Python, after they were disabled by an imported module

我有以下片段:

a = np.array([1, 2, 3])
b = np.array([False, True])
print(a[b])

它按预期触发了 VisibleDeprecationWarning

现在当我导入某个模块时,该警告不再显示:

import questionable_module
a = np.array([1, 2, 3])
b = np.array([False, True])
print(a[b])

我需要如何修改我的代码才能重新启用所有警告?我不想也不能改变questionable_module。如果可能的话,我更愿意在代码中而不是在命令行参数中执行此操作。

questionable_moduleGlumpy,但我正在寻找一种独立于其他模块工作的解决方案。

我检查了一下,似乎 glumpy 他们使用 logging.captureWarnings 来捕获警告:

import warnings
import logging
logging.captureWarnings(True)

Source

我不确定他们是否打算记录所有警告,但您可以使用

禁用它
import logging
logging.captureWarnings(False)

其他可能性(不适用于这种情况)但将来可能会有所帮助:

一般来说也可能是他们调整了warnings.simplefilter你可以像这样再次启用它:

import warnings
warnings.simplefilter("always", VisibleDeprecationWarning)

或使用 warnings.resetwarnings 将其重置为默认值。

如果它实际上是一个 NumPy 浮点警告你,那么你需要使用 numpy.seterr:

import numpy as np
np.seterr(all='warn')

但也可能是 questionable_module 确实 以它们实际上 从来没有 的方式替换或修补了函数到达发出警告的地步。在那种情况下你可能什么也做不了。

试试这个:

import warnings
import questionable_module
warnings.resetwarnings() # Reset the warnings filter. This discards the effect of all previous calls to filterwarnings(), including that of the -W command line options and calls to simplefilter().
warnings.simplefilter('default')
a = np.array([1, 2, 3])
b = np.array([False, True])
print(a[b])