无法取消弃用警告 [英] Unable to suppress deprecation warnings
问题描述
在我的Django应用程序中,当我导入一个第三方库时,在控制台中收到以下警告:
In my Django application, when I import one third party library, I get this warning in the console:
imp模块是不推荐使用importlib;请参阅该模块的文档以供其他用途
the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
但是,如果我在Python shell中进行导入,则一切正常。我想在Django中实现相同的行为。这是我根据其他操作系统线程中的答案所尝试的:
If however I do the import inside Python shell, then everything is ok. I want to achive the same behaviour in Django. This is what I've tried based on answers in other OS threads:
import warnings
from django.utils.deprecation import RemovedInDjango110Warning
warnings.filterwarnings(action="ignore", category=RemovedInDjango110Warning)
上面的代码导致另一个错误消息,指出RemovedInDjango110Warning不存在。我也尝试过这样:
The above code results in another error message, that says that RemovedInDjango110Warning does not exists. I also tried this:
import warnings
def fxn():
warnings.warn("deprecated", DeprecationWarning)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
fxn()
from third_party_lib import some_module
但是我仍然得到非常相同的错误消息。因此,似乎以前所有对此问题的答案都已过时。我们需要一些新的解决方法。谢谢!
But still I get the very same error message. So, it seems like all previous answers to this problem got outdated. And we need some fresh fix. Thanks!
我也尝试过:
import warnings
with warnings.catch_warnings():
warnings.filterwarnings("ignore",category=DeprecationWarning)
from third_party_lib import some_module
但是没有效果。
推荐答案
有一个您尝试过的代码有几个问题。如果要过滤 PendingDeprecationWarning
,则应在代码中使用 PendingDeprecationWarning
。您的代码使用的是 DeprecationWarning
和 RemovedInDjango110Warning
,它们是不同的警告。其次,文档中的 fxn()
函数是一个创建警告的示例函数。
There are a couple of issues with the code you've tried. If you want to filter PendingDeprecationWarning
, then you should use PendingDeprecationWarning
in your code. Your code is using DeprecationWarning
and RemovedInDjango110Warning
, which are different warnings. Secondly, the fxn()
function in the docs is an example function that creates a warning. It doesn't make sense to include it in your code.
您可以过滤所有未决的弃用警告
You can either filter all pending deprecation warnings
import warnings
warnings.simplefilter("ignore", category=PendingDeprecationWarning)
但是,这可能会在您应该修复的代码中隐藏未决的弃用。更好的方法是使用上下文管理器,在导入第三方库时过滤掉警告。
However this might hide pending deprecations in your own code that you should fix. A better approach would be to use a context manager, to filter out warnings when importing the third-party lib.
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=PendingDeprecationWarning)
from third_party_lib import some_module
这篇关于无法取消弃用警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!