如何在保持所有其他警告正常的同时去除 python 中的特定警告消息?

我正在用一个 Python 脚本做一些简单的数学运算,得到了以下警告:

“警告: 除以零,在除法中遇到”。

为了提供一些上下文,我取了两个值,试图找出值 (a - b) / a的百分比差异,如果它高于某个范围,那么处理它,但有时 ab的值为零。

我想摆脱这个特定的警告(在一个特定的行) ,但所有的信息,我发现迄今似乎告诉我如何停止所有的警告(我不想)。

当我过去编写 shell 脚本时,我可以这样做

code...
more code 2 > error.txt
even more code

在这个示例中,我将获得“ code”和“ even more code”命令的警告,但不会获得第二行的警告。

这可能吗?

39149 次浏览

我一开始就会避免零除法:

if a == 0:
# Break out early


# Otherwise the ratio makes sense

如果您确实希望将这个特定的 numpy 警告压缩到一行中,numpy 提供了 一条路:

with numpy.errstate(divide='ignore'):
# The problematic line

如果 Scipy 正在使用 warnings模块,那么可以禁止显示特定的警告。在你的程序开始的时候试试这个:

import warnings
warnings.filterwarnings("ignore", message="divide by zero encountered in divide")

如果您希望这只应用于代码的一个部分,那么使用警告上下文管理器:

import warnings
with warnings.catch_warnings():
warnings.filterwarnings("ignore", message="divide by zero encountered in divide")
# .. your divide-by-zero code ..

搅拌机的答案完全符合这个问题。也许有人对另一种通用方法感兴趣,这种方法可以使用 regex 或行号捕获特定的警告:

压制由特定行引起的警告,这里第113行:

import warnings
warnings.simplefilter('ignore',lineno=113)

这种方法有一个缺点,那就是每次修改代码中的某些内容时,都需要重新调整 lineno。另一种选择是使用正则表达式捕获警告。将返回以下代码

import warnings
warnings.filterwarnings('ignore', message='.*show', )
warnings.warn('Do not do this!')
warnings.warn('Do not show this message')
>>> UserWarning: Do not do this!
warnings.warn('Do not do this!')

* 符号前的点是必需的,否则将返回错误

error: nothing to repeat

这是讨论在这个 线