Python - 用简单的消息替换警告

Python - Replacing warnings with a simple message

我已经从 sklearn 构建了一些现成的分类器,并且有一些预期的场景,我知道分类器必然会表现不佳并且无法正确预测任何事情。 sklearn.svm 程序包运行时没有错误,但会引发以下警告。

~/anaconda/lib/python3.5/site-packages/sklearn/metrics/classification.py:1074: UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 due to no predicted samples.
  'precision', 'predicted', average, warn_for)

我希望禁止显示此警告,而是将消息替换为 stdout,例如 "poor classifier performance"

一般情况下有什么方法可以抑制warnings吗?

使用 -Wignore 可以轻松抑制所有警告(参见 warning flag docs

warnings 模块可以使用过滤器进行一些更精细的调整(仅忽略您的警告类型)。

捕获只是你的警告(假设模块中没有一些API来调整它)并做一些特别的事情可以使用warnings.catch_warnings context manager and code adapted from "Testing Warnings":

import warnings

class MyWarning(Warning):
    pass

def something():
    warnings.warn("magic warning", MyWarning)

with warnings.catch_warnings(record=True) as w:
    # Trigger a warning.
    something()
    # Verify some things
    if ((len(w) == 1) 
            and issubclass(w[0].category, MyWarning) 
            and "magic" in str(w[-1].message)):
        print('something magical')