如何禁用 Python 警告?
- 2024-12-05 08:37:00
- admin 原创
- 142
问题描述:
我正在使用该库编写的代码会抛出很多(目前对我来说)无用的警告warnings
。阅读(/扫描)文档后,我只找到了一种禁用单个函数警告的方法。但我不想更改太多代码。
有没有像这样的旗帜python -no-warning foo.py
?
你会推荐什么?
解决方案 1:
查看Python 文档的暂时抑制警告部分:
如果您正在使用知道会引发警告的代码(例如已弃用的函数),但又不想看到该警告,那么可以使用
catch_warnings
上下文管理器来抑制该警告:import warnings def fxn(): warnings.warn("deprecated", DeprecationWarning) with warnings.catch_warnings(): warnings.simplefilter("ignore") fxn() # Or if you are using > Python 3.11: with warnings.catch_warnings(action="ignore"): fxn()
我不能容忍这种行为,但你可以用这个来抑制所有警告:
import warnings
warnings.filterwarnings("ignore")
前任:
>>> 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
解决方案 2:
有-W
選擇。
python -W ignore foo.py
解决方案 3:
为了不使它复杂化,只需使用顶部的这两行
import warnings
warnings.filterwarnings('ignore')
解决方案 4:
您还可以定义一个环境变量(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')
>>>
对于弃用警告,请查看how-to-ignore-deprecation-warnings-in-python
复制到这里...
来自warnings
模块的文档:
#!/usr/bin/env python -W ignore::DeprecationWarning
如果您使用的是 Windows:将其-W ignore::DeprecationWarning
作为参数传递给 Python。不过,解决问题的最好方法是转换为int。
(请注意,在 Python 3.2 中,默认会忽略弃用警告。)
或者:
import warnings
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=DeprecationWarning)
import md5, sha
yourcode()
现在您仍然可以获得所有其他DeprecationWarning
s,但不会有由以下原因引起的问题:
import md5, sha
解决方案 5:
如果你不想弄得太复杂,那么:
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
解决方案 6:
当所有其他方法都失败时,请使用这个: https: //github.com/polvoazul/shutup
pip install shutup
然后添加到代码顶部:
import shutup; shutup.please()
免责声明:我是该存储库的所有者。我在第五次需要它并且找不到任何简单有效的方法后写了它。
解决方案 7:
这是一个老问题,但PEP 565中有一些较新的指导,如果您正在编写 python 应用程序,则应使用以下方法关闭所有警告:
import sys
import warnings
if not sys.warnoptions:
warnings.simplefilter("ignore")
python -W
建议这样做的原因是它默认关闭所有警告,但关键的是允许通过命令行或将它们重新打开PYTHONWARNINGS
。
解决方案 8:
如果您知道通常会遇到哪些无用的警告,则可以通过消息进行过滤。
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")
解决方案 9:
import sys
if not sys.warnoptions:
import warnings
warnings.simplefilter("ignore")
在处理文件或添加新功能时更改为重新启用ignore
警告。default
解决方案 10:
我意识到这只适用于少数情况,但在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
最好的部分是您可以仅将其应用于非常特定的代码行。
解决方案 11:
例如,您可以忽略此警告:
InsecureRequestWarning:正在向主机发出未经验证的 HTTPS 请求...
import warnings
warnings.filterwarnings(
action="ignore",
message=".*Unverified HTTPS.*",
)
解决方案 12:
忽略警告的更 Python 方式
由于“ warning.filterwarnings() ”没有抑制所有警告,我建议您使用以下方法:
import logging
for name in logging.Logger.manager.loggerDict.keys():
logging.getLogger(name).setLevel(logging.CRITICAL)
#rest of the code starts here...
或者,
如果您只想抑制一组特定的警告,那么您可以按如下方式进行过滤:
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...
解决方案 13:
我编写了一个装饰器,可以很容易地忽略特定函数定义中的警告:
import functools
import warnings
from typing import Callable
def ignore_warnings(category: Warning):
def ignore_warnings_decorator(func: Callable):
@functools.wraps(func)
def wrapper(*args, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=category)
return func(*args, **kwargs)
return wrapper
return ignore_warnings_decorator
使用示例:
@ignore_warnings(category=DeprecationWarning)
def foo() -> None:
# imagine this function below would throw a deprecation
# warning that we willfully want to ignore because we know better:
bar()
解决方案 14:
警告通过 stderr 输出,简单的解决方案是附加到命令中。
2> /dev/null
或者,将错误重定向到文件,这样就可以保留它们而不会弄脏控制台输出。
2> my-cli-errors.log