如何知道Python中的警告来源
有没有办法在警告信息旁边显示行号呢?我收到了几个警告,可能是来自numpy库,但我不知道这些警告是从哪里来的。我不想让我的代码停止运行或者抛出异常,但我希望能获得更多关于这些警告来源的信息。这种事情可以做到吗?
3 个回答
0
编辑:
哎呀!我莫名其妙地把名字搞错了。
请使用 pychecker 模块。如果你已经安装了 distutils,那么只需在命令行输入:easy_install pychecker
就可以获取最新版本。默认情况下,它会生成警告,并列出这些警告的行号。
2
写一个这样的独立模块。
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
2
通过 warnings
模块发出的警告,默认情况下会显示文件名和行号,你可以通过 warnings
模块里的函数或者 Python 解释器的 -W
参数来控制这些输出。因为你的警告似乎没有包含文件名和行号,所以 warnings
模块可能对你没有帮助。你怀疑是 numpy
造成的问题,我建议你看看 numpy.seterr()
这个函数。也许把警告变成错误会有帮助。