【发布时间】:2019-06-20 02:57:20
【问题描述】:
我相信这个问题已经被提出过很多次了,但我有一个特定的用例,我无法用网络上描述的许多方法解决这个问题。
在我的一个项目中,我使用joblib 库,它显示DeprecationWarning,因为它在内部某处使用imp 库:
from sklearn.externals.joblib import Parallel, delayed
def main():
xs = Parallel()(delayed(lambda x: x**2)(i) for i in range(1, 6))
print(sum(xs))
if __name__ == '__main__':
main()
我正在尝试使用解释器选项 -W 过滤掉警告,但它没有帮助:
$ python -W ignore example.py
[...]/lib/python3.7/site-packages/sklearn/externals/joblib/externals/cloudpickle/cloudpickle.py:47:
DeprecationWarning: the imp module is deprecated in favour of importlib;
see the module's documentation for alternative uses import imp
55
另外,我正在尝试使用 warnings 模块进行显式过滤,但它也无济于事:
import warnings
warnings.simplefilter('ignore', category=DeprecationWarning)
from sklearn.externals.joblib import Parallel, delayed
def main():
xs = Parallel()(delayed(lambda x: x**2)(i) for i in range(1, 6))
print(sum(xs))
if __name__ == '__main__':
main()
matplotlib 模块和其他一些第三方库也有类似的问题。可能还有其他一些方法(即环境变量),但我不明白为什么这些解决方案不起作用。
谁能解释警告系统在 Python 中的实际工作原理?第三方库有可能故意覆盖客户端的警告设置吗?我想说这个问题对我来说是最晦涩的话题之一。
【问题讨论】:
-
找到它:诀窍是在导入 sklearn(或使用 sklearn 的依赖项)时使用“with”警告:
with warnings.catch_warnings(): warnings.simplefilter("ignore", category=DeprecationWarning) import hdbscan这将仅禁用此模块的 DeprecationWarning。 -
@Alex 您介意将your second comment 中嵌入的有用技巧推断为正确答案吗?然后,我们所有人都会将其投票支持平流层。 (想想可能属于你的业力荣耀。)
-
请参阅下面的答案以获取解决方案