Charles Brunet
Charles Brunet

Reputation: 23160

How to know where warning come from in Python

Is it possible to display line number along with warnings? I'm getting some warnings, possibly from numpy, but I have no idea where they come from. I don't want my code to aboard or to raise an exception, but I'd like to get more information from the origin of the warnings. Is it something possible?

Upvotes: 2

Views: 856

Answers (3)

Spencer Rathbun
Spencer Rathbun

Reputation: 14910

EDIT:

Arg! I inexplicably got the name wrong.

Use the pychecker module. If you have distutils installed, then just type: easy_install pychecker on the command line to get the newest version. By default in generates warnings, and lists the line numbers for them.

Upvotes: 0

Sven Marnach
Sven Marnach

Reputation: 602625

Warnings that are issued via the warnings module are by default printed including file name and line number, and the output can be controlled by the functions in the warnings module as well as by the -W parameter to the Python interpreter. Since your warnings apparently don't include file name and line number, the warnings module probably won't help you. Since you suspect that numpy might be the culprit, I suggest having a look at the numpy.seterr() function. Maybe turning warnings into errors helps.

Upvotes: 2

kindall
kindall

Reputation: 184395

Write a separate module like this.

import warnings

# capture all warnings
with warnings.catch_warnings(record=True) as warns:
    warnings.simplefilter("always")
    # do the stuff that triggers warnings.  i.e. import your main module
    # and call whatever is necessary to get it going.  This must all be
    # indented under the with statement!

# afterward, print captured warnings
for w in warns:
    print w.category.__name__, "(%s)" % w.message,
    print "in", w.filename, "at line", w.lineno

Upvotes: 3

Related Questions