”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > Python 中的警告过滤器

Python 中的警告过滤器

发布于2024-11-08
浏览:185

Warning Filter in Python

Buy Me a Coffee☕

*My post explains Warning with warn() in Python.

A warnings filter can set which warnings to show using these filters(actions) below. *"once" may not work properly:

Value Disposition
"default" print the first occurrence of matching warnings for each location (module line number) where the warning is issued
"error" turn matching warnings into exceptions
"ignore" never print matching warnings
"always" always print matching warnings
"module" print the first occurrence of matching warnings for each module where the warning is issued (regardless of line number)
"once" print only the first occurrence of matching warnings, regardless of location

By default, these filters below are set to warnings.filters and they can be reset with resetwarnings() as shown below:

import warnings

print(warnings.filters)
# [('default', None, , '__main__', 0),
#  ('ignore', None, , None, 0),
#  ('ignore', None, , None, 0),
#  ('ignore', None, , None, 0),
#  ('ignore', None, , None, 0)]

warnings.resetwarnings()

print(warnings.filters)
# []

Now, filterwarnings() or simplefilter() can filter warnings as shown below:

*Memos for filterwarnings():

  • The 1st argument is action(Required-Type:str). *"default", "error", "ignore", "always", "module" or "once" can be set.
  • The 2nd argument is message(Optional-Default:""-Type:str).
  • The 3rd argument is category(Optional-Default:Warning-Type:Warning).
  • The 4th argument is module(Optional-Default:""-Type:str). *It may not work properly.
  • The 5th argument is lineno(Optional-Default:0-Type:int): *Memos:
    • It decides a line number.
    • It must be x >= 0.
  • The 6th argument is append(Optional-Default:False-Type:bool). *If it's False, a filter is add before other filters while if it's True, a filter is add after other filters.

*Memos for simplefilter():

  • The 1st argument is action(Required-Type:str). *"default", "error", "ignore", "always", "module" or "once" can be set.
  • The 2nd argument is category(Optional-Default:Warning-Type:Warning).
  • The 3rd argument is lineno(Optional-Default:0-Type:int): *Memos:
    • It decides a line number.
    • It must be x >= 0.
  • The 4th argument is append(Optional-Default:False-Type:bool). *If it's False, a filter is add before other filters while if it's True, a filter is add after other filters.
my_project
 |-main.py
 |-file1.py(module)
 └-file2.py(module)

file1.py:

import warnings                                                 # Line 1
                                                                # Line 2
warnings.warn(message="Warning 1", category=UserWarning)        # Line 3
warnings.warn(message="Warning 2", category=DeprecationWarning) # Line 4
warnings.warn(message="Warning 2", category=DeprecationWarning) # Line 5
warnings.warn(message="Warning 3", category=UserWarning)        # Line 6

file2.py:

import warnings                                                 # Line 1
                                                                # Line 2
warnings.warn(message="Warning 1", category=UserWarning)        # Line 3
warnings.warn(message="Warning 2", category=DeprecationWarning) # Line 4
warnings.warn(message="Warning 2", category=DeprecationWarning) # Line 5
warnings.warn(message="Warning 3", category=UserWarning)        # Line 6

main.py with "default" filter(action):

import warnings

warnings.resetwarnings()

warnings.filterwarnings(action="default")
warnings.filterwarnings(action="default", message="", category=Warning,
                        module="", lineno=0, append=False)
warnings.simplefilter(action="default")
warnings.simplefilter(action="default", category=Warning,
                      lineno=0, append=False)
print(warnings.filters)
# [('default', None, , None, 0)]

import file1, file2
# ...\my_project\file1.py:3: UserWarning: Warning 1
#   warnings.warn(message="Warning 1", category=UserWarning)
# ...\my_project\file1.py:4: DeprecationWarning: Warning 2
#   warnings.warn(message="Warning 2", category=DeprecationWarning)
# ...\my_project\file1.py:5: DeprecationWarning: Warning 2
#   warnings.warn(message="Warning 2", category=DeprecationWarning)
# ...\my_project\file1.py:6: UserWarning: Warning 3
#   warnings.warn(message="Warning 3", category=UserWarning)
# ...\my_project\file2.py:3: UserWarning: Warning 1
#   warnings.warn(message="Warning 1", category=UserWarning)
# ...\my_project\file2.py:4: DeprecationWarning: Warning 2
#   warnings.warn(message="Warning 2", category=DeprecationWarning)
# ...\my_project\file2.py:5: DeprecationWarning: Warning 2
#   warnings.warn(message="Warning 2", category=DeprecationWarning)
# ...\my_project\file2.py:6: UserWarning: Warning 3
#   warnings.warn(message="Warning 3", category=UserWarning)

main.py with "error" filter(action):

import warnings

warnings.resetwarnings()

warnings.filterwarnings(action="error")
warnings.simplefilter(action="error")

print(warnings.filters)
# [('error', None, , None, 0)]

import file1, file2
# ...\my_project\file1.py", line 3, in 
#     warnings.warn(message="Warning 1", category=UserWarning)
# UserWarning: Warning 1

main.py with "ignore" filter(action):

import warnings

warnings.resetwarnings()

warnings.filterwarnings(action="ignore")
warnings.simplefilter(action="ignore")

print(warnings.filters)
# [('ignore', None, , None, 0)]

import file1, file2 # Warnings are not shown
import warnings

warnings.resetwarnings()

warnings.filterwarnings(action="ignore", category=UserWarning)
warnings.simplefilter(action="ignore", category=UserWarning)

print(warnings.filters)
# [('ignore', None, , None, 0)]

import file1, file2
# ...\my_project\file1.py:4: DeprecationWarning: Warning 2
#   warnings.warn(message="Warning 2", category=DeprecationWarning)
# ...\my_project\file1.py:5: DeprecationWarning: Warning 2
#   warnings.warn(message="Warning 2", category=DeprecationWarning)
# ...\my_project\file2.py:4: DeprecationWarning: Warning 2
#   warnings.warn(message="Warning 2", category=DeprecationWarning)
# ...\my_project\file2.py:5: DeprecationWarning: Warning 2
#   warnings.warn(message="Warning 2", category=DeprecationWarning)
import warnings

warnings.resetwarnings()

warnings.filterwarnings(action="ignore", message="Warning 1", 
                        category=UserWarning)
print(warnings.filters)
# [('ignore', re.compile('Warning 1', re.IGNORECASE),
#  , None, 0)]

import file1, file2
# ...\my_project\file1.py:4: DeprecationWarning: Warning 2
#   warnings.warn(message="Warning 2", category=DeprecationWarning)
# ...\my_project\file1.py:5: DeprecationWarning: Warning 2
#   warnings.warn(message="Warning 2", category=DeprecationWarning)
# ...\my_project\file1.py:6: UserWarning: Warning 3
#   warnings.warn(message="Warning 3", category=UserWarning)
# ...\my_project\file2.py:4: DeprecationWarning: Warning 2
#   warnings.warn(message="Warning 2", category=DeprecationWarning)
# ...\my_project\file2.py:5: DeprecationWarning: Warning 2
#   warnings.warn(message="Warning 2", category=DeprecationWarning)
# ...\my_project\file2.py:6: UserWarning: Warning 3
#   warnings.warn(message="Warning 3", category=UserWarning)
import warnings

warnings.resetwarnings()

warnings.filterwarnings(action="ignore", lineno=6)
warnings.simplefilter(action="ignore", lineno=6)

print(warnings.filters)
# [('ignore', None, , None, 6)]

import file1, file2
# ...\my_project\file1.py:3: UserWarning: Warning 1
#   warnings.warn(message="Warning 1", category=UserWarning)
# ...\my_project\file1.py:4: DeprecationWarning: Warning 2
#   warnings.warn(message="Warning 2", category=DeprecationWarning)
# ...\my_project\file1.py:5: DeprecationWarning: Warning 2
#   warnings.warn(message="Warning 2", category=DeprecationWarning)
# ...\my_project\file2.py:3: UserWarning: Warning 1
#   warnings.warn(message="Warning 1", category=UserWarning)
# ...\my_project\file2.py:4: DeprecationWarning: Warning 2
#   warnings.warn(message="Warning 2", category=DeprecationWarning)
# ...\my_project\file2.py:5: DeprecationWarning: Warning 2
#   warnings.warn(message="Warning 2", category=DeprecationWarning)

main.py with "always" filter(action):

import warnings

warnings.resetwarnings()

warnings.filterwarnings(action="always")
warnings.simplefilter(action="always")

print(warnings.filters)
# [('always', None, , None, 0)]

import file1, file2
# ...\my_project\file1.py:3: UserWarning: Warning 1
#   warnings.warn(message="Warning 1", category=UserWarning)
# ...\my_project\file1.py:4: DeprecationWarning: Warning 2
#   warnings.warn(message="Warning 2", category=DeprecationWarning)
# ...\my_project\file1.py:5: DeprecationWarning: Warning 2
#   warnings.warn(message="Warning 2", category=DeprecationWarning)
# ...\my_project\file1.py:6: UserWarning: Warning 3
#   warnings.warn(message="Warning 3", category=UserWarning)
# ...\my_project\file2.py:3: UserWarning: Warning 1
#   warnings.warn(message="Warning 1", category=UserWarning)
# ...\my_project\file2.py:4: DeprecationWarning: Warning 2
#   warnings.warn(message="Warning 2", category=DeprecationWarning)
# ...\my_project\file2.py:5: DeprecationWarning: Warning 2
#   warnings.warn(message="Warning 2", category=DeprecationWarning)
# ...\my_project\file2.py:6: UserWarning: Warning 3
#   warnings.warn(message="Warning 3", category=UserWarning)

main.py with "module" filter(action):

import warnings

warnings.resetwarnings()

warnings.filterwarnings(action="module")
warnings.simplefilter(action="module")

print(warnings.filters)
# [('module', None, , None, 0)]

import file1, file2
# ...\my_project\file1.py:3: UserWarning: Warning 1
#   warnings.warn(message="Warning 1", category=UserWarning)
# ...\my_project\file1.py:4: DeprecationWarning: Warning 2
#   warnings.warn(message="Warning 2", category=DeprecationWarning)
# ...\my_project\file1.py:6: UserWarning: Warning 3
#   warnings.warn(message="Warning 3", category=UserWarning)
# ...\my_project\file2.py:3: UserWarning: Warning 1
#   warnings.warn(message="Warning 1", category=UserWarning)
# ...\my_project\file2.py:4: DeprecationWarning: Warning 2
#   warnings.warn(message="Warning 2", category=DeprecationWarning)
# ...\my_project\file2.py:6: UserWarning: Warning 3
#   warnings.warn(message="Warning 3", category=UserWarning)

main.py with "once" filter(action):

import warnings

warnings.resetwarnings()

warnings.filterwarnings(action="once")
warnings.simplefilter(action="once")

print(warnings.filters)
# [('once', None, , None, 0)]

import file1, file2
# ...\my_project\file1.py:3: UserWarning: Warning 1
#   warnings.warn(message="Warning 1", category=UserWarning)
# ...\my_project\file1.py:4: DeprecationWarning: Warning 2
#   warnings.warn(message="Warning 2", category=DeprecationWarning)
# ...\my_project\file1.py:6: UserWarning: Warning 3
#   warnings.warn(message="Warning 3", category=UserWarning)
# ...\my_project\file2.py:3: UserWarning: Warning 1
#   warnings.warn(message="Warning 1", category=UserWarning)
# ...\my_project\file2.py:4: DeprecationWarning: Warning 2
#   warnings.warn(message="Warning 2", category=DeprecationWarning)
# ...\my_project\file2.py:6: UserWarning: Warning 3
#   warnings.warn(message="Warning 3", category=UserWarning)

main.py with append argument. *If append=False, a filter is add before other filters while if append=True, a filter is add after other filters:

import warnings

warnings.resetwarnings()

print(warnings.filters)
# []

warnings.filterwarnings(action="default", append=False)
warnings.simplefilter(action="default", append=False)

print(warnings.filters)
# [('default', None, , None, 0)]

warnings.filterwarnings(action="always", append=False)
warnings.simplefilter(action="always", append=False)

print(warnings.filters)
# [('always', None, , None, 0),
#  ('default', None, , None, 0)]

warnings.filterwarnings(action="once", append=True)
warnings.simplefilter(action="once", append=True)

print(warnings.filters)
# [('always', None, , None, 0),
#  ('default', None, , None, 0),
#  ('once', None, , None, 0)]
版本声明 本文转载于:https://dev.to/hyperkai/warning-filter-in-python-4g0e?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 哪种方法更有效地用于点 - 填点检测:射线跟踪或matplotlib \的路径contains_points?
    哪种方法更有效地用于点 - 填点检测:射线跟踪或matplotlib \的路径contains_points?
    在Python Matplotlib's path.contains_points FunctionMatplotlib's path.contains_points function employs a path object to represent the polygon.它...
    编程 发布于2025-03-12
  • VS Code & Delve 调试Go代码:Build Tags配置指南
    VS Code & Delve 调试Go代码:Build Tags配置指南
    在Visual Studio Code中使用标签进行调试,并在使用构建标签来编译GO程序的各种版本时,请在delve debugger 中使用,这对于配置DEBUGGER以配置最佳debugger以进行最佳利用。标签:在Visual Studio Code的GO插件中指定构建标签,您可以使用bui...
    编程 发布于2025-03-12
  • 如何在JavaScript对象中动态设置键?
    如何在JavaScript对象中动态设置键?
    在尝试为JavaScript对象创建动态键时,如何使用此Syntax jsObj['key' i] = 'example' 1;不工作。正确的方法采用方括号: jsobj ['key''i] ='example'1; 在JavaScript中,数组是一...
    编程 发布于2025-03-12
  • HTML格式标签
    HTML格式标签
    HTML 格式化元素 **HTML Formatting is a process of formatting text for better look and feel. HTML provides us ability to format text without us...
    编程 发布于2025-03-12
  • 为什么尽管有效代码,为什么在PHP中捕获输入?
    为什么尽管有效代码,为什么在PHP中捕获输入?
    在php ;?>" method="post">The intention is to capture the input from the text box and display it when the submit button is clicked.但是,输出...
    编程 发布于2025-03-12
  • 为什么不使用CSS`content'属性显示图像?
    为什么不使用CSS`content'属性显示图像?
    在Firefox extemers属性为某些图像很大,&& && && &&华倍华倍[华氏华倍华氏度]很少见,却是某些浏览属性很少,尤其是特定于Firefox的某些浏览器未能在使用内容属性引用时未能显示图像的情况。这可以在提供的CSS类中看到:。googlepic { 内容:url(&#...
    编程 发布于2025-03-12
  • 为什么我会收到MySQL错误#1089:错误的前缀密钥?
    为什么我会收到MySQL错误#1089:错误的前缀密钥?
    mySQL错误#1089:错误的前缀键错误descript [#1089-不正确的前缀键在尝试在表中创建一个prefix键时会出现。前缀键旨在索引字符串列的特定前缀长度长度,可以更快地搜索这些前缀。了解prefix keys `这将在整个Movie_ID列上创建标准主键。主密钥对于唯一识别...
    编程 发布于2025-03-12
  • \“(1)vs.(;;):编译器优化是否消除了性能差异?\”
    \“(1)vs.(;;):编译器优化是否消除了性能差异?\”
    答案: 在大多数现代编译器中,while(1)和(1)和(;;)之间没有性能差异。编译器: perl: 1 输入 - > 2 2 NextState(Main 2 -E:1)V-> 3 9 Leaveloop VK/2-> A 3 toterloop(next-> 8 last-> 9 ...
    编程 发布于2025-03-12
  • 为什么PYTZ最初显示出意外的时区偏移?
    为什么PYTZ最初显示出意外的时区偏移?
    与pytz 最初从pytz获得特定的偏移。例如,亚洲/hong_kong最初显示一个七个小时37分钟的偏移: 差异源利用本地化将时区分配给日期,使用了适当的时区名称和偏移量。但是,直接使用DateTime构造器分配时区不允许进行正确的调整。 example pytz.timezone(...
    编程 发布于2025-03-12
  • Laravel要去:我的旅程和纤维API样板的创建
    Laravel要去:我的旅程和纤维API样板的创建
    花费四年以上,我对MVC(Model-View-Controller)架构非常熟悉。它的简单性和结构使与之合作变得很高兴,而Laravel的有条理的文件夹可帮助开发人员保持正轨。您始终知道将代码放置在哪里,以及广泛的内置工具 - 数据库连接,redis,排队,迁移,ORM等等 - 将设置无缝。只需...
    编程 发布于2025-03-12
  • 如何使用替换指令在GO MOD中解析模块路径差异?
    如何使用替换指令在GO MOD中解析模块路径差异?
    在使用GO MOD时,在GO MOD 中克服模块路径差异时,可能会遇到冲突,其中可能会遇到一个冲突,其中3派对软件包将另一个带有导入套件的path package the Imptioned package the Imptioned package the Imported tocted pac...
    编程 发布于2025-03-12
  • 如何为PostgreSQL中的每个唯一标识符有效地检索最后一行?
    如何为PostgreSQL中的每个唯一标识符有效地检索最后一行?
    postgresql:为每个唯一标识符在postgresql中提取最后一行,您可能需要遇到与数据集合中每个不同标识的信息相关的信息。考虑以下数据:[ 1 2014-02-01 kjkj 在数据集中的每个唯一ID中检索最后一行的信息,您可以在操作员上使用Postgres的有效效率: id dat...
    编程 发布于2025-03-12
  • 对象拟合:IE和Edge中的封面失败,如何修复?
    对象拟合:IE和Edge中的封面失败,如何修复?
    To resolve this issue, we employ a clever CSS solution that solves the problem:position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%)...
    编程 发布于2025-03-12
  • 如何从PHP中的数组中提取随机元素?
    如何从PHP中的数组中提取随机元素?
    从阵列中的随机选择,可以轻松从数组中获取随机项目。考虑以下数组:; 从此数组中检索一个随机项目,利用array_rand( array_rand()函数从数组返回一个随机键。通过将$项目数组索引使用此键,我们可以从数组中访问一个随机元素。这种方法为选择随机项目提供了一种直接且可靠的方法。
    编程 发布于2025-03-12
  • 在Java中使用for-to-loop和迭代器进行收集遍历之间是否存在性能差异?
    在Java中使用for-to-loop和迭代器进行收集遍历之间是否存在性能差异?
    For Each Loop vs. Iterator: Efficiency in Collection TraversalIntroductionWhen traversing a collection in Java, the choice arises between using a for-...
    编程 发布于2025-03-12

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3