无法抑制弃用警告

Jac*_*ian 4 python django

在我的Django应用程序中,当我导入一个第三方库时,我在控制台中收到此警告:

不推荐使用imp模块以支持importlib; 有关其他用途,请参阅模块的文档

但是,如果我在Python shell中进行导入,那么一切都很好.我想在Django中实现相同的行为.这是我根据其他操作系统线程中的答案尝试的:

import warnings
from django.utils.deprecation import RemovedInDjango110Warning
warnings.filterwarnings(action="ignore", category=RemovedInDjango110Warning)
Run Code Online (Sandbox Code Playgroud)

上面的代码导致另一条错误消息,表明RemovedInDjango110Warning不存在.我也试过这个:

import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxn()

from third_party_lib import some_module
Run Code Online (Sandbox Code Playgroud)

但我仍然收到相同的错误消息.所以,似乎此问题的所有先前答案都已过时.我们需要一些新的解决方案.谢谢!

我也试过这个:

import warnings

with warnings.catch_warnings():
    warnings.filterwarnings("ignore",category=DeprecationWarning)
    from third_party_lib import some_module
Run Code Online (Sandbox Code Playgroud)

但它没有效果.

Ala*_*air 6

您尝试过的代码存在一些问题.如果要过滤PendingDeprecationWarning,则应PendingDeprecationWarning在代码中使用.你的代码是使用DeprecationWarning和RemovedInDjango110Warning,这是不同的警告.其次,fxn()docs中的函数是一个创建警告的示例函数.将它包含在代码中是没有意义的.

您可以过滤所有待处理的弃用警告

import warnings
warnings.simplefilter("ignore", category=PendingDeprecationWarning)
Run Code Online (Sandbox Code Playgroud)

但是,这可能会隐藏您应该修复的自己的代码中的待处理弃用.更好的方法是使用上下文管理器,在导入第三方库时过滤掉警告.

with warnings.catch_warnings():
    warnings.simplefilter("ignore", category=PendingDeprecationWarning)
    from third_party_lib import some_module
Run Code Online (Sandbox Code Playgroud)