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

是否有类似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")

有-W选项。

python -W ignore foo.py

不要让它变得复杂,只需使用这两行

import warnings
warnings.filterwarnings('ignore')

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

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

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