Make Python `warnings.warn ()` not mention itself

My minimal example

#!/usr/bin/python3

import warnings

warnings.warn('Run Forest run!', stacklevel=2)
warnings.warn('Run Forest run!')

and he will output

sys:1: UserWarning: Run Forest run!
./file.py:6: UserWarning: Run Forest run!
  warnings.warn('Run Forest run!')

The first line gives me some information. The second line is perfect, giving me the source file and line number ... but I would like to get rid of the extra third line. Is it possible?

+4
source share
3 answers

It turns out that you can allow warnings.warn()to collect all the information and just program the way to print information:

#!/usr/bin/python3

import warnings

def warning_on_one_line(message, category, filename, lineno, file=None, line=None):
    return '%s:%s: %s: %s\n' % (filename, lineno, category.__name__, message)

warnings.formatwarning = warning_on_one_line

warnings.warn('Run Forest run!', stacklevel=2)
warnings.warn('Run Forest run!')

Conclusion:

sys:1: UserWarning: Run Forest run!
./file.py:15: UserWarning: Run Forest run!

Source: Python module of the week

+4
source

, "" , , stacklevel, stacklevel 1, , , warnings.warn('Run Forest Run!').

, , warnings.warn_explicit() .

https://docs.python.org/3.1/library/warnings.html#available-functions

+4

/ , , traceback.print_exc():

import traceback
import warnings

def _formatwarning(msg, *a):
   try:
       traceback.print_exc()
   except:
       pass
   return str(msg)

warnings.formatwarning = _formatwarning

( " " ) , warn().

UPDATE: on Python 3.6 you need to change the function signature to:

def _formatwarning(message, category, filename, lineno, line='')
+2
source

All Articles