6

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!" ?

2
  • 4
    If you only want the last line to be outputed, why not print it? Commented Dec 21, 2016 at 18:35
  • 2
    have you tried warnings.showwarning = send_warnings_to_log? Commented Dec 21, 2016 at 18:38

1 Answer 1

14

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Why when I am setting stacklevel=2 I am getting this error? 'File "C:\Users\...\Python\Python35\lib\idlelib\run.py", line 351 exec(code, self.locals)'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.