Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python warnings stack levels

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()
like image 727
Leos Kotrop Avatar asked Aug 31 '25 10:08

Leos Kotrop


1 Answers

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

like image 113
Serge Ballesta Avatar answered Sep 02 '25 22:09

Serge Ballesta