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

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

你会推荐什么?


当前回答

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

import warnings
warnings.filterwarnings('ignore')

其他回答

当所有其他操作都失败时,请使用以下选项: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...

有-W选项。

python -W ignore foo.py

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

我意识到这只适用于特定的情况,但在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

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