开发者

How to know where warning come from in Python

开发者 https://www.devze.com 2023-03-13 14:19 出处:网络
Is it possible to display line number along with warnings? I\'m getting some warnings, possi开发者_JAVA百科bly from numpy, but I have no idea where they come from. I don\'t want my code to aboard or t

Is it possible to display line number along with warnings? I'm getting some warnings, possi开发者_JAVA百科bly 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?


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消