17

I have a code which, at some point shows a warning, I think that it is having a problem calculating a mean()

I would like to know if there is any way to force python to tell me where, or which line, or whatever more information than just this message:

C:\Python27\lib\site-packages\numpy\core\_methods.py:55: RuntimeWarning: Mean of empty slice.
  warnings.warn("Mean of empty slice.", RuntimeWarning)
C:\Python27\lib\site-packages\numpy\core\_methods.py:79: RuntimeWarning: Degrees of freedom <= 0 for slice
  warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning)

I do not know if it is possible to "catch" a warning.....If I have any error, usually I am using traceback package:

import traceback

And then I usually do:

try:
    #something
except:
    print traceback.format_exc()
codeKiller
  • 5,493
  • 17
  • 60
  • 115
  • possible duplicate of [Get Traceback of warnings](http://stackoverflow.com/questions/22373927/get-traceback-of-warnings) – Korem Jul 01 '14 at 14:43

1 Answers1

37

You can turn warnings into exceptions:

import warnings

warnings.simplefilter("error")

Now instead of printing a warning, an exception will be raised, giving you a traceback.

You can get the same effect with the -W command line switch:

$ python -W error somescript.py

or by setting the PYTHONWARNINGS environment variable:

$ export PYTHONWARNINGS=error

You can play with the other warnings.simplefilter() arguments to be more specific about what warning should raise an exception. You could filter on warnings.RuntimeWarning and a line number, for example.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • what are the pros and cons of the first 2 options? The third seems more extreme – 3pitt Jan 18 '18 at 18:01
  • @MikePalmice: all 3 options have the exact same effect, they are just different ways of signalling to the Python binary to change the filter settings. – Martijn Pieters Jan 18 '18 at 18:34