我正在处理使用警告库抛出大量(对我来说)无用警告的代码。阅读(/扫描)文档时,我只找到了禁用单个函数警告的方法。但我不想更改这么多代码。

是否有类似python的标志-没有警告foo.py?

你会推荐什么?


当前回答

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

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

其他回答

您还可以定义一个环境变量(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')
>>> 

有关弃用警告,请查看如何忽略python中的弃用警告

复制到此处。。。

从警告模块的文档中:

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

如果您在Windows上:pass-W ignore::DeprecationWarning作为Python的参数。不过,最好通过向int转换来解决问题。

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

Or:

import warnings

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

yourcode()

现在,您仍然会收到所有其他DeprecationWarnings,但不会收到以下原因导致的警告:

import md5, sha

查看Python文档的“临时抑制警告”部分:

如果您使用的代码已知会引发警告,例如已弃用的函数,但不希望看到警告,则可以使用catch_warnings上下文管理器抑制警告:导入警告def fxn():warnings.warn(“已弃用”,弃用警告)带有警告。catch_warnings():warnings.simplefilter(“忽略”)fxn()

我不宽恕它,但你可以这样压制所有警告:

import warnings
warnings.filterwarnings("ignore")

Ex:

>>> 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

当所有其他操作都失败时,请使用以下选项:https://github.com/polvoazul/shutup

管道安装关闭

然后在代码顶部添加:

import shutup; shutup.please()

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


忽略警告的更像蟒蛇的方式


由于“warning.filterwarnings()”未抑制所有警告,我建议您使用以下方法:

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

#rest of the code starts here...

OR,

如果希望仅抑制一组特定的警告,则可以按如下方式进行过滤:

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...

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

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