我正在处理使用警告库抛出大量(对我来说)无用警告的代码。阅读(/扫描)文档时,我只找到了禁用单个函数警告的方法。但我不想更改这么多代码。
是否有类似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...
其他回答
如果你知道你通常会遇到哪些无用的警告,你可以通过消息过滤它们。
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")
如果你不想要复杂的东西,那么:
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
这是一个老问题,但PEP 565中有一些新的指导,如果您正在编写python应用程序,请关闭所有警告:
import sys
import warnings
if not sys.warnoptions:
warnings.simplefilter("ignore")
建议这样做的原因是,它默认关闭所有警告,但关键是允许通过命令行上的python-W或PYTHONWARNINGS重新打开警告。
不要让它变得复杂,只需使用这两行
import warnings
warnings.filterwarnings('ignore')
我意识到这只适用于特定的情况,但在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
最好的一点是,您只能将其应用于非常特定的代码行。