654

我正在处理使用该warnings库引发很多(目前对我而言)无用警告的代码。阅读(/扫描)文档我只找到了一种禁用单个功能警告的方法。但我不想更改太多代码。

有没有类似的标志python -no-warning foo.py

你会推荐什么?

4

12 回答 12

851

查看 Python 文档的Temporarily Suppressing Warnings部分:

如果您使用的代码您知道会引发警告,例如不推荐使用的函数,但不想看到警告,则可以使用catch_warnings上下文管理器抑制警告:

import warnings

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

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

我不宽恕它,但你可以用这个来压制所有警告

import warnings
warnings.filterwarnings("ignore")

前任:

>>> import warnings
>>> def f():
...     print('before')
...     warnings.warn('you are warned!')
...     print('after')
...
>>> f()
before
<stdin>:3: UserWarning: you are warned!
after
>>> warnings.filterwarnings("ignore")
>>> f()
before
after
于 2013-01-22T16:31:00.393 回答
549

-W选项

python -W ignore foo.py
于 2013-01-22T16:28:31.550 回答
145

您还可以定义环境变量(2010 年的新功能 - 即 python 2.7)

export PYTHONWARNINGS="ignore"

像这样测试:默认

$ export PYTHONWARNINGS="default"
$ python
>>> import warnings
>>> warnings.warn('my warning')
__main__:1: UserWarning: my warning
>>>

忽略警告

$ export PYTHONWARNINGS="ignore"
$ python
>>> import warnings
>>> warnings.warn('my warning')
>>> 

对于弃用警告,请查看how-to-ignore-deprecation-warnings-in-python

复制到这里...

warnings模块的文档:

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

如果您在 Windows 上:-W ignore::DeprecationWarning作为参数传递给 Python。最好通过强制转换为int来解决问题。

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

或者:

import warnings

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

yourcode()

现在你仍然得到所有其他DeprecationWarning的,但不是由以下原因引起的:

import md5, sha
于 2013-07-15T12:59:26.220 回答
94

如果您不想要复杂的东西,那么:

import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
于 2018-12-13T14:07:53.680 回答
89

这是一个老问题,但是PEP 565中有一些更新的指导,如果你正在编写一个你应该使用的 python 应用程序,可以关闭所有警告:

import sys
import warnings

if not sys.warnoptions:
    warnings.simplefilter("ignore")

推荐这样做的原因是它默认关闭所有警告,但至关重要的是允许它们通过python -W命令行或PYTHONWARNINGS.

于 2018-02-06T18:48:40.087 回答
51

不复杂,就用这两行

import warnings
warnings.filterwarnings('ignore')
于 2021-06-16T20:36:53.360 回答
34

如果您知道您通常遇到的无用警告是什么,您可以通过消息对其进行过滤。

import warnings

#ignore by message
warnings.filterwarnings("ignore", message="divide by zero encountered in divide")

#part of the message is also okay
warnings.filterwarnings("ignore", message="divide by zero encountered") 
warnings.filterwarnings("ignore", message="invalid value encountered")
于 2019-05-15T06:25:34.770 回答
32

当所有其他方法都失败时,请使用:https ://github.com/polvoazul/shutup

pip install shutup

然后添加到代码的顶部:

import shutup; shutup.please()

免责声明:我是该存储库的所有者。我在第五次需要这个之后写了它,但找不到任何简单的东西。

于 2021-06-29T20:13:14.510 回答
7
import sys
if not sys.warnoptions:
    import warnings
    warnings.simplefilter("ignore")

在处理文件或添加新功能以重新启用警告时将忽略更改为默认值。

于 2021-02-26T10:18:11.770 回答
5

我意识到这仅适用于某些情况,但在numpy我真正喜欢使用的上下文中np.errstate

np.sqrt(-1)
__main__:1: RuntimeWarning: invalid value encountered in sqrt
nan

但是,使用np.errstate

with np.errstate(invalid='ignore'):
    np.sqrt(-1)
nan

最好的部分是您只能将其应用于非常特定的代码行。

于 2020-05-25T21:32:35.923 回答
3

更多pythonic方式来忽略警告


由于 ' warning.filterwarnings() ' 没有抑制所有警告,我建议你使用以下方法:

import logging
    
for name in logging.Logger.manager.loggerDict.keys():
    logging.getLogger(name).setLevel(logging.CRITICAL)

#rest of the code starts here...

或者,

如果您只想抑制一组特定的警告,那么您可以像这样过滤:

import logging
    
for name in logging.Logger.manager.loggerDict.keys():
    if ('boto' in name) or ('urllib3' in name) or ('s3transfer' in name) or ('boto3' in name) or ('botocore' in name) or ('nose' in name):
            logging.getLogger(name).setLevel(logging.CRITICAL)

#rest of the code starts here...
于 2021-01-13T15:54:05.467 回答
-9

警告通过 stderr 输出,简单的解决方案是将“2> /dev/null”附加到 CLI。这对许多用户来说很有意义,例如那些使用 centos 6 的用户,他们坚持使用 python 2.6 依赖项(如 yum),并且各种模块在其覆盖范围内被推到灭绝的边缘。

对于涉及 SNI 等的密码学尤其如此。可以使用 proc 更新 2.6 以进行 HTTPS 处理: https ://urllib3.readthedocs.io/en/latest/user-guide.html#ssl-py2

警告仍然存在,但是您想要的所有内容都已向后移植。尽管 stdout 内容本身不会改变,但 stderr 的重定向将为您提供干净的终端/shell 输出。

回应 FriendFX。第一 (1) 句以通用解决方案直接回应问题。第二 (2) 句考虑了引用的锚点重新“禁用警告”,这是特定于 python 2.6 的,并指出 RHEL/centos 6 用户不能直接不使用 2.6。尽管没有引用具体警告,但第二 (2) 段回答了我最常遇到的 2.6 问题,即密码学模块中的缺点以及如何“现代化”(即升级、反向移植、修复)python 的 HTTPS/TLS 性能. 第三 (3) 段仅解释了使用重定向和升级模块/依赖项的结果。

于 2017-01-23T02:43:40.967 回答