python - 在警告被抑制后控制警告的出现

标签 python warnings

考虑一下:

>>> import warnings
>>> warnings.filterwarnings("always", category=DeprecationWarning)
>>> warnings.warn("Hello", DeprecationWarning)
/usr/bin/bpython:2: DeprecationWarning: Hello

好的,那里有警告。

>>> warnings.filterwarnings("ignore", category=DeprecationWarning)
>>> warnings.warn("Silence", DeprecationWarning)

这里没有警告。

>>> warnings.filterwarnings("always", category=DeprecationWarning)
>>> warnings.warn("Silence", DeprecationWarning) # why remain silent?
>>>

这里没有警告,但是我所看到的应该有一个警告。如果您删除 python 2 和 3 上的“忽略”过滤器,也会发生同样的情况。

虽然原则上这不应该是一个问题(除非有其他原因),但我在不知情的情况下在某处创建了这个静音警告。这使得很难确定警告是否在给定的警告上下文中得到控制。

注意:在脚本中,此示例运行良好。然而,我原来的问题可能只与这个例子类似,所以我怀疑它仅限于交互式提示。在最初的问题中,即使 warnings.filters 中的第一个过滤器应与“always”匹配(我检查过),我也没有看到任何警告。

最佳答案

好的,所以我想这个具体问题实际上是由这个 bug report 回答的。 。不幸的是,这似乎并不是我的问题,但那是另一回事......

如果有人感兴趣...我最初的问题只是由于忘记了 warnings.filters 使用正则表达式 re.match 并且需要开始要匹配的字符串。

在测试函数的弃用警告时避免出现此问题

if hasattr(function, '__globals__'):
    if function.__globals__.has_key('__warningregistry__'):
        function.__globals__['__warningregistry__'].clear()

这至少对我来说有帮助。 (在测试另一个警告时忽略了一个警告,然后在测试第一个被忽略的警告时触发了此问题)

关于python - 在警告被抑制后控制警告的出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14207178/

相关文章:

c++ - 如何禁用来自非项目文件的警告? --- Visual Studio 2010

ios - Swift 编译器警告 : Result of call to 'save(defaults:)' is unused

matlab - 警告 : "Parethesize the multiplication of ' D' and its transpose to ensure the result is Hermetian.“

Python 碎片 : How to return nothing if xpath doesn't exist?

python - 在列 * 和 * 索引上使用 groupby 和聚合与 Pandas 数据框

php - 任何编程语言的分布式并行编程模型——类似于apach hadoop但支持windows机器

node.js - 链中有 .catch 但使用 Node 6 得到 UnhandledPromiseRejectionWarning

c++ - 在 XCode 中发出未使用的参数警告

python - Plotly:使用 plotly express line 时如何在 hoverinfo 中格式化日期?

python - 将字符串函数应用于 pandas 数据框列