我正在处理使用警告库抛出大量(对我来说)无用警告的代码。阅读(/扫描)文档时,我只找到了禁用单个函数警告的方法。但我不想更改这么多代码。
是否有类似python的标志-没有警告foo.py?
你会推荐什么?
我正在处理使用警告库抛出大量(对我来说)无用警告的代码。阅读(/扫描)文档时,我只找到了禁用单个函数警告的方法。但我不想更改这么多代码。
是否有类似python的标志-没有警告foo.py?
你会推荐什么?
当前回答
忽略警告的更像蟒蛇的方式
由于“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...
其他回答
当所有其他操作都失败时,请使用以下选项:https://github.com/polvoazul/shutup
管道安装关闭
然后在代码顶部添加:
import shutup; shutup.please()
免责声明:我是该存储库的所有者。我在第五次需要它后写了它,但找不到任何简单的东西。
您还可以定义一个环境变量(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
这是一个老问题,但PEP 565中有一些新的指导,如果您正在编写python应用程序,请关闭所有警告:
import sys
import warnings
if not sys.warnoptions:
warnings.simplefilter("ignore")
建议这样做的原因是,它默认关闭所有警告,但关键是允许通过命令行上的python-W或PYTHONWARNINGS重新打开警告。
忽略警告的更像蟒蛇的方式
由于“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
#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")