我总是听到这个:

DeprecationWarning: integer argument expected, got float

我怎样才能让这条信息消失?在Python中有避免警告的方法吗?


当前回答

Python 3

在编写代码之前,只需在下面写下容易记住的行:

import warnings

warnings.filterwarnings("ignore")

其他回答

来自警告模块的文档:

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

如果你在Windows上:传递-W ignore::DeprecationWarning作为Python的参数。不过更好的解决方法是强制转换为int类型。

(注意,在Python 3.2中,默认情况下会忽略弃用警告。)

你应该修改你的代码,但以防万一,

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

注释掉下面文件中的警告行:

lib64/python2.7/site-packages/cryptography/__init__.py

并不是要痛打你,而是警告你,当你下次升级python时,你正在做的事情可能会停止工作。转换为int并完成它。

顺便说一句。您还可以编写自己的警告处理程序。只要分配一个什么都不做的函数。 如何重定向python警告自定义流?

当您希望仅忽略函数中的警告时,可以执行以下操作。

import warnings
from functools import wraps


def ignore_warnings(f):
    @wraps(f)
    def inner(*args, **kwargs):
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("ignore")
            response = f(*args, **kwargs)
        return response
    return inner

@ignore_warnings
def foo(arg1, arg2):
    ...
    write your code here without warnings
    ...

@ignore_warnings
def foo2(arg1, arg2, arg3):
    ...
    write your code here without warnings
    ...

只需在想要忽略所有警告的函数上添加@ignore_warnings装饰器