如何在保持其他警告正常的情况下去除Python中特定的警告信息?

91 投票
4 回答
58761 浏览
提问于 2025-04-17 12:17

我在一个Python脚本里做一些简单的数学运算,结果遇到了一个警告:

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

给你们提供点背景信息,我正在计算两个数值之间的百分比差异,公式是 (a - b) / a,如果这个差异超过某个范围,就会继续处理。但是,有时候 ab 的值是零。

我想要去掉这个特定行的警告,但我找到的信息大多是教我怎么关闭所有警告(我并不想这样做)。

以前我写shell脚本的时候,可以这样做:

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

在那个例子里,我会收到'code'和'even more code'命令的警告,但第二行的警告就不会出现。

这样做有可能吗?

4 个回答

9

Blender的回答非常符合这个问题。也许有人对另一种通用的方法感兴趣,这种方法可以通过正则表达式或行号来捕捉特定的警告:

比如说,想要抑制由特定行引起的警告,这里是第113行:

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

这种方法的缺点是,每次你修改代码时,都需要重新调整行号。另一种选择是使用正则表达式来捕捉警告。以下代码将返回

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

这个问题在这个讨论帖中有讨论

194

如果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 ..
19

我建议你首先避免出现除以零的情况:

if a == 0:
    # Break out early

# Otherwise the ratio makes sense

如果你确实想在一行代码中消除这个特定的numpy警告,numpy提供了一种方法

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

撰写回答