I am trying the warning message doesn't include the source line that generated it, using warnings stack levels, but instead of seeing only the message, I am getting one more line which says:
File "sys", line 1
Is possible not to get this line?
This is my code:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import warnings
def warning_function():
warnings.warn("Python 3.x is required!", RuntimeWarning, stacklevel = 8)
if sys.version_info[0] < 3:
...
else:
warning_function()
Well that's exactly what you asked for: the stacklevel=8
parameter requires to unwind 7 calls between showing the current line. As you have not that number of calls, you end in the starting of Python interpreter.
If you want further control on the printed string, you should overwrite the warnings.showwarning
function:
old_fw = warnings.showwarning # store previous function...
def new_sw(message, category, filename, lineno, file = None, line = None):
msg = warnings.formatwarning(message, category, filename, lineno,
line).split(':')[-2:]
sys.stderr.write("Warning (from warnings module):\n{}:{}\n".format(
msg[0][1:], msg[1]))
warnings.showwarning = new_sw
That way you will not have the File "...", line ...
line
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