Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python warning message output

With this code:

#! /usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import warnings

if sys.version_info[0] >= 3:
    ...
else:
    warnings.warn("Python 3.x is required!", RuntimeWarning)

And the else output I get is:

Warning (from warnings module):
  File "C:\Users\..., line 10
    warnings.warn("Python 3.x is required!", RuntimeWarning)
RuntimeWarning: Python 3.x is required!

Is there any way of getting rid of the first 3 lines of the output and only display "RuntimeWarning: Python 3.x is required!" ?

like image 719
K. Leontis Avatar asked Dec 21 '16 18:12

K. Leontis


1 Answers

from https://pymotw.com/2/warnings/#stack-level-in-warnings

Stack Level in Warnings

You’ll notice that by default the warning message includes the source line that generated it, when available. It’s not all that useful to see the line of code with the actual warning message, though. Instead, you can tell warn() how far up the stack it has to go to find the line the called the function containing the warning. That way users of a deprecated function see where the function is called, instead of the implementation of the function.

# warnings_warn_stacklevel.py
import warnings

def old_function():
    warnings.warn(
        'old_function() is deprecated, use new_function() instead', 
        stacklevel=2)

def caller_of_old_function():
    old_function()

caller_of_old_function() 

Notice that in this example warn() needs to go up the stack 2 levels, one for itself and one for old_function().

$ python warnings_warn_stacklevel.py

warnings_warn_stacklevel.py:18: UserWarning: old_function() is deprecated, use new_function() instead   old_function()
like image 100
ArmenB Avatar answered Nov 02 '22 23:11

ArmenB