gpt4 book ai didi

python - 无法抑制弃用警告

转载 作者:太空狗 更新时间:2023-10-30 02:41:00 26 4
gpt4 key购买 nike

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

the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses

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

import warnings
from django.utils.deprecation import RemovedInDjango110Warning
warnings.filterwarnings(action="ignore", category=RemovedInDjango110Warning)

以上代码导致了另一条错误消息,指出 RemovedInDjango110Warning 不存在。我也试过这个:

import warnings

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

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

from third_party_lib import some_module

但我仍然收到完全相同的错误消息。因此,似乎以前对此问题的所有答案都已过时。我们需要一些新的修复。谢谢!

我也试过这个:

import warnings

with warnings.catch_warnings():
warnings.filterwarnings("ignore",category=DeprecationWarning)
from third_party_lib import some_module

但是没有效果。

最佳答案

您试过的代码有几个问题。如果要过滤 PendingDeprecationWarning,则应在代码中使用 PendingDeprecationWarning。您的代码使用了 DeprecationWarningRemovedInDjango110Warning,它们是不同的警告。其次,文档中的 fxn() 函数是一个创建警告的示例函数。将它包含在您的代码中没有意义。

您可以过滤所有未决的弃用警告

import warnings
warnings.simplefilter("ignore", category=PendingDeprecationWarning)

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

with warnings.catch_warnings():
warnings.simplefilter("ignore", category=PendingDeprecationWarning)
from third_party_lib import some_module

关于python - 无法抑制弃用警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40993553/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com