用户警告的堆栈跟踪 [英] Stacktrace for UserWarning
问题描述
我在日志中看到这样的警告:
I see a warning like this in my logs:
py.warnings.__init__: WARNING .../bs4/__init__.py:219: UserWarning: "foo"
looks like a filename, not markup. You should probably open this file
and pass the filehandle into Beautiful Soup
这条消息没有多大帮助.
This message does not help very much.
我想查看发生这种情况的堆栈跟踪.
I would like to see the stacktrace where this happens.
请不要查看此警告的内容.这个问题与美汤无关 :-)
Please don't look into the content of this warning. This question is not about Beautiful Soup :-)
一个简单的解决方案是修改第三方代码(bs4/__init__.py
在第 219 行)并添加如下内容:
An easy solution would be to modify the third party code (bs4/__init__.py
at line 219) and add something like this:
import traceback
logger.warn('Exc at ...\n%s' % ''.join(traceback.format_stack()))
但我想避免这种情况.原因:
But I would like to avoid this. Reasons:
- 这是来自生产系统的警告.我不想改变来源.
- 下次出现这样的警告时,我想立即看到堆栈跟踪
是否有我可以更改的 python 标志或设置,不仅可以查看一行,还可以查看 while 堆栈跟踪?我需要上面的框架来调试这个.
Is there a flag or setting for python which I can change, to see not only one line, but the while stacktrace? I need the upper frames to debug this.
在此环境中使用 Python 2.7.
In this environment Python 2.7 gets used.
推荐答案
您需要执行以下操作:
- 如果 USER_SITE 不存在则创建:发出
python -c "import site; site._script()"
,查看 USER_SITE 变量内容 在该目录中放置一个文件
usercustomize.py
,代码如下:
- Create if USER_SITE does not exists: issue
python -c "import site; site._script()"
, see USER_SITE variable contents Place a file
usercustomize.py
in that directory with the following code:
import traceback
import warnings
_old_warn = warnings.warn
def warn(*args, **kwargs):
tb = traceback.extract_stack()
_old_warn(*args, **kwargs)
print("".join(traceback.format_list(tb)[:-1]))
warnings.warn = warn
感谢 this 对代码的回答.
Credits to this answer for the code.
照常运行代码.我的测试代码:
Run the code as usual. My test code:
import warnings
def f():
warnings.warn("foz")
f()
手术前:
$ python test_warn.py
test_warn.py:4: UserWarning: foz
warnings.warn("foz")
之后:
$ python test_warn.py
<USER_SITE_REDACTED>/usercustomize.py:6: UserWarning: foz
_old_warn(*args, **kwargs)
File "test_warn.py", line 6, in <module>
f()
File "test_warn.py", line 4, in f
warnings.warn("foz")
这篇关于用户警告的堆栈跟踪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!