python内置模块warnings,警告模块

一、简介

warnings 模块是 Python 标准库中的一个模块,用于处理警告信息。它提供了一种机制,可以让开发者在代码中发出警告,以提醒用户潜在的问题或不推荐的用法。使用
warnings 模块可以帮助开发者在代码中标记潜在的问题,并提供一些控制警告行为的选项。

二、方法
  1. warnings.warn(*args, **kwargs):用于发出警告。
  • *args 的位置参数如下:
  • message:作为第一个位置参数,可以是一个字符串,用于指定警告消息的内容。
  • category:作为第二个位置参数(可选),用于指定警告的类别。如果未提供,默认为 Warning 类别。
  • **kwargs的关键字参数如下:
  • category:指定警告的类别。可以是一个警告类的实例,用于自定义警告类别。默认为 Warning。
  • filename:指定发出警告的文件名。
  • lineno:指定发出警告的行号。
  • module:指定发出警告的模块名。
  • source:指定发出警告的源代码。
import warnings

def divide(a, b):
    if b == 0:
        warnings.warn("Dividing by zero is not recommended.", category=RuntimeWarning)
    return a / b

result = divide(10, 0)
print(result)
  1. warnings.warn_explicit(*args, **kwargs):函数用于显式地发出警告,提供了更详细的控制选项。
  • *args 的位置参数如下:
  • message:作为第一个位置参数,可以是一个字符串,用于指定警告消息的内容。
  • category:作为第二个位置参数(可选),用于指定警告的类别。如果未提供,默认为 Warning 类别。
  • **kwargs的关键字参数如下:
  • category:指定警告的类别。可以是一个警告类的实例,用于自定义警告类别。默认为 Warning。
  • filename:指定发出警告的文件名。
  • lineno:指定发出警告的行号。
  • module:指定发出警告的模块名。
  • source:指定发出警告的源代码。
def divide(a, b):
    if b == 0:
        filename = "example.py"        lineno = 10        category = UserWarning        warnings.warn_explicit("Dividing by zero is not recommended.", category, filename, lineno)
    return a / bresult = divide(10, 0)
print(result)
  1. warnings.filterwarnings(action, message=“”, category=Warning, module=“”, lineno=0, append):用于控制警告行为。
  • action:字符串,表示要执行的操作。可以是以下值之一:
  • ‘error’:将警告视为错误,抛出 Warnings 异常。
  • ‘ignore’:忽略警告,不显示警告信息。
  • ‘always’:始终显示警告信息。
  • ‘default’:使用默认的警告显示方式,通常是显示一次。
  • ‘module’:只显示来自指定模块的警告。
  • ‘once’:只显示每个警告类型的第一次出现的警告。
  • message:字符串,用于指定要匹配的警告消息。如果不指定,则匹配所有警告消息。
  • category:警告类别。默认为 Warning 类。
  • module:字符串,用于指定要匹配的模块名。如果不指定,则匹配所有模块。
  • lineno:整数,用于指定要匹配的行号。如果不指定,则匹配所有行号。
import warnings

# 定义一个自定义的警告类
class CustomWarning(Warning):
    pass

# 设置警告过滤器
warnings.filterwarnings('error', category=CustomWarning, module='my_module', lineno=10)

# 抛出一个警告
warnings.warn('This is a custom warning', category=CustomWarning, module='my_module', lineno=10)

  1. warnings.formatwarning(message, category, filename, lineno, line):用于自定义警告消息的格式。
  • message:字符串,表示警告消息。
  • category:警告类别。
  • filename:字符串,表示发出警告的文件名。
  • lineno:整数,表示发出警告的行号。
  • line:字符串,表示发出警告的源代码行。
import warnings

# 自定义警告格式化函数
def custom_formatwarning(message, category, filename, lineno, line):
    return f"Custom Warning: {message} ({filename}:{lineno})\n"

# 设置警告格式化函数
warnings.formatwarning = custom_formatwarning

# 抛出一个警告
warnings.warn("This is a custom warning", category=UserWarning)
  1. warnings.simplefilter(action, category=Warning, lineno=0, append=False):filterwarnings() 函数的简化版本
  2. warnings.resetwarnings():用于重置警告设置为默认值。
三、警告类别
  1. Warning:所有警告类的基类。
  2. UserWarning:用户定义的警告类。
  3. DeprecationWarning:关于已弃用功能的警告。
  4. PendingDeprecationWarning:关于即将弃用功能的警告。
  5. SyntaxWarning:语法相关的警告。
  6. RuntimeWarning:运行时警告,通常指示潜在的问题或错误。
  7. FutureWarning:关于可能在未来版本中更改的警告。
  8. ImportWarning:关于导入模块时的警告。
  9. UnicodeWarning:与 Unicode 相关的警告。
  10. BytesWarning:与字节序列相关的警告。
  11. ResourceWarning:与资源管理相关的警告。
四、其他
  1. warnings.WarningMessage.ssage:警告消息的文本内容。
  2. warnings.WarningMessage.line:警告消息所在的源代码行的文本内容。
  3. warnings.WarningMessage.lineno:警告消息所在的源代码行号。
  4. warnings.WarningMessage.filename:包含警告消息的源代码文件名。
  5. warnings.WarningMessage.file:包含警告消息的源代码文件对象。
  6. warnings.WarningMessage.category:警告消息的类别。
  7. warnings.WarningMessage.source:警告消息的源代码文本内容。
  8. warnings.catch_warnings(record=False, module=None,action=None, category=Warning, lineno=0, append):上下文管理器,用于捕获并记录警告消息
  • record:指定是否记录捕获的警告消息。如果设置为 True,则警告消息将被记录在一个列表中,可以通过 warnings.catch_warnings() 返回的上下文管理器的 warnings 属性访问。如果设置为 False,则警告消息将只是简单地被捕获,而不会记录下来。
  • module:指定要应用警告过滤器的模块对象。如果设置为 None,则默认为当前模块。
  • action:指定警告处理的动作。可以是一个函数或字符串。如果是一个函数,它将被调用以处理每个捕获的警告消息。如果是一个字符串,它可以是以下值之一:
  • ‘error’:将警告消息视为异常,并引发 Warning 类型的异常。
  • ‘ignore’:忽略警告消息,不进行任何处理。
  • ‘always’:始终打印警告消息,而不管警告过滤器的设置。
  • category:指定要捕获的警告类别。可以是一个警告类别或警告类别的元组。如果设置为 Warning,则捕获所有警告。
  • lineno:指定警告消息所在的源代码行号。如果设置为 0,则不进行行号匹配。
  • append:指定是否将警告消息追加到警告列表的末尾。如果设置为 True,则新的警告消息将追加到列表末尾。如果设置为 False,则新的警告消息将插入到列表的开头。
  1. warnings.filters.count(value):返回过滤器列表中等于 value 的元素的数量。
  2. warnings.filters.index(value, start, stop):返回过滤器列表中第一个等于 value 的元素的索引。可以指定搜索的起始位置 start 和结束位置 stop。
import warnings

def custom_warning_function():
    warnings.warn("This is a custom warning")

with warnings.catch_warnings(record=True) as warning_list:
    custom_warning_function()
    warning = warning_list[0]

print(warning.message)
print(warning.line)
print(warning.lineno)
print(warning.filename)
print(warning.file)
print(warning.category)
print(warning.source)

# 获取警告过滤器列表中的数量和索引
filter_count = warnings.filters.count()
filter_index = warnings.filters.index('default')
print(filter_count)
print(filter_index)
### 使用Python `warnings` 库 #### 抑制警告信息 当程序中存在已知会触发警告的部分,但希望暂时不显示这些警告消息时,可以利用 `catch_warnings()` 上下文管理器来实现局部范围内的警告抑制功能。例如: ```python import warnings def deprecated_function(): warnings.warn("This function is deprecated.", DeprecationWarning) with warnings.catch_warnings(): warnings.simplefilter("ignore") deprecated_function() ``` 上述代码片段展示了如何在一个特定的作用域内忽略所有的警告信息[^1]。 #### 调整全局警告过滤规则 为了改变整个应用程序对于不同类型警告行为的方式,可以通过调用 `filterswarnings()` 函数并传入相应的参数来进行配置。下面的例子说明了怎样让弃用警告重新变为可见状态: ```python import warnings # 将DeprecationWarning恢复为默认的行为(即打印出来) warnings.filterwarnings("default", category=DeprecationWarning) ``` 这使得即使是在交互式解释器或其他环境中被静默处理过的弃用警告也能再次显现出来。 #### 命令行方式控制警告 除了编程接口外,还可以通过启动 Python 解释器时传递 `-W` 选项来自定义警告过滤策略。比如想要完全忽视某类警告,则可以在命令行执行如下指令: ```bash $ python3 -W "ignore:do not:UserWarning::0" script.py ``` 此操作将会使脚本中的用户自定义警告不再输出至终端窗口[^2]。 #### 动态调整警告级别 有时可能需要动态地修改当前环境下的警告设置而不影响其他部分的工作流程;这时就可以考虑使用 `simplefilter()` 方法配合不同的动作名称(action name)。以下是几个常见的应用场景及其对应的语法结构: - **ignore**: 完全屏蔽符合条件的消息; - **module**: 每个模块仅报告一次相同类型的警告; - **once**: 整个项目生命周期里只展示一条相匹配的通知。 具体应用实例可参照官方文档获取更多信息[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

局外人LZ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值