如何忽略Python中的弃用警告

266 投票
18 回答
362768 浏览
提问于 2025-04-15 11:40

我总是看到这个信息:

DeprecationWarning: integer argument expected, got float

我该怎么才能让这个信息消失呢?有没有办法在Python中避免这些警告?

18 个回答

242

我之前遇到这些问题:

/home/eddyp/virtualenv/lib/python2.6/site-packages/Twisted-8.2.0-py2.6-linux-x86_64.egg/twisted/persisted/sob.py:12:
DeprecationWarning: the md5 module is deprecated; use hashlib instead import os, md5, sys

/home/eddyp/virtualenv/lib/python2.6/site-packages/Twisted-8.2.0-py2.6-linux-x86_64.egg/twisted/python/filepath.py:12:
DeprecationWarning: the sha module is deprecated; use the hashlib module instead import sha

我用以下方法解决了:

import warnings

with warnings.catch_warnings():
    warnings.filterwarnings("ignore",category=DeprecationWarning)
    import md5, sha

yourcode()

现在你还是会看到其他的 DeprecationWarning 警告,但不会再看到由以下原因引起的警告:

import md5, sha
321

你应该直接修复你的代码,不过以防万一,

import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning) 
153

来自warnings模块的文档:

 #!/usr/bin/env python -W ignore::DeprecationWarning

如果你在使用Windows系统,可以在运行Python时加上参数-W ignore::DeprecationWarning,这样就可以忽略那些过时警告。不过,更好的办法是解决这个问题,方法是将数据转换为整数

(注意,在Python 3.2版本中,过时警告默认是被忽略的。)

撰写回答