Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

traceback from a warning

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()
like image 928
codeKiller Avatar asked Jul 01 '14 14:07

codeKiller


People also ask

What is traceback Python?

In Python, A traceback is a report containing the function calls made in your code at a specific point i.e when you get an error it is recommended that you should trace it backward(traceback). Whenever the code gets an exception, the traceback will give the information about what went wrong in the code.

How do I ignore runtime warnings in Python?

In order to temporarily suppress warnings, set simplefilter to 'ignore'.

What is warning in Python?

A warning in a program is distinct from an error. Python program terminates immediately if an error occurs. Conversely, a warning is not critical. It shows some message, but the program runs. The warn() function defined in the ' warning ' module is used to show warning messages.

What does deprecation warning mean in Python?

removing is danger because user may used that and if a developer want to remove a thing first have to notify others to don't use this feature or things and after this he can remove. and DeprecationWarning is this notification.


1 Answers

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.

like image 180
Martijn Pieters Avatar answered Sep 28 '22 00:09

Martijn Pieters