从警告回溯 [英] traceback from a warning

查看:24
本文介绍了从警告回溯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码,在某些时候显示警告,我认为它在计算 mean()

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

我想知道是否有任何方法可以强制 python 告诉我在哪里,或哪一行,或者除了这条消息之外的更多信息:

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:

导入回溯

然后我通常会这样做:

try:
    #something
except:
    print traceback.format_exc()

推荐答案

您可以将警告转化为异常:

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.

您可以使用 -W 命令行开关:

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

$ python -W error somescript.py

或通过设置 PYTHONWARNINGS 环境变量:

or by setting the PYTHONWARNINGS environment variable:

$ export PYTHONWARNINGS=error

您可以使用其他 warnings.simplefilter() arguments 更具体地说明什么警告应该引发异常.例如,您可以过滤 warnings.RuntimeWarning 和行号.

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.

这篇关于从警告回溯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆