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!" ?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With