How does Python catch warnings? (Note: not to catch the exception)

1. The warning is not an exception

Do you often use some system libraries or third-party modules, and there will be some warning messages that are neither exceptions nor errors?

These warning messages, sometimes very many, can easily cause some misjudgments for novices, thinking that the program is wrong.

In fact, it is not the case. Exceptions and errors are some problems in the program, but the warning is different. Its urgency is very low, so that most of the warnings can be directly ignored.

If you don't want to display these alarm information, you can directly add the parameter -W ignore parameter, and it will no longer be displayed.

2. Can warnings be caught?

Only error exceptions can be caught, but after a series of operations, you can turn these warnings into exceptions.

In this way, you can catch them like an exception.

Without any settings, the warning will be printed directly on the terminal.

 

3. Method one to catch warning

There are a series of filters in warnings.

When you specify as error, the matching warning will be converted into an exception.

Then you can catch the warning by exception.

import warnings
warnings.filterwarnings('error')    

try:
    warnings.warn("deprecated", DeprecationWarning)
except Warning as e:
    print(e)

After running, the effect is as follows

 

4. The second method of catching warnings

If you don't want to configure it in the code, turn the warning into an exception.

import warnings

try:
    warnings.warn("deprecated", DeprecationWarning)
except Warning as e:
    print(e)

When executing, just add a parameter -W error, you can achieve the same effect

$ python3 -W error demo.py
deprecated

5. The third method of catching warnings

In addition to the above methods, warnings also comes with a context manager to capture warnings.

When you add record=True, it will return a list, in which all the captured warnings are stored. I assign it to w, and then it can be printed out.

import warnings

def do_warning():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings(record=True) as w:
    do_warning()
    if len(w) >0:
        print(w[0].message)

After running, the effect is as follows

 

I still want to recommend the Python learning group I built myself : 705933274. The group is all learning Python. If you want to learn or are learning Python, you are welcome to join. Everyone is a software development party and share dry goods from time to time (only Python software development related), including a copy of the latest Python advanced materials and zero-based teaching compiled by myself in 2021. Welcome friends who are in advanced and interested in Python to join!

 

Guess you like

Origin blog.csdn.net/pyjishu/article/details/114748759