获取引发异常的异常描述和堆栈跟踪,全部为字符串 [英] Get exception description and stack trace which caused an exception, all as a string

查看:134
本文介绍了获取引发异常的异常描述和堆栈跟踪,全部为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python中看到很多有关堆栈跟踪和异常的帖子。但是没有找到我需要的。



我有一大堆Python 2.7代码可能引发异常。我想抓住它,并分配一个字符串其完整的描述和导致错误的堆栈跟踪(只是我们在控制台上看到的全部)。我需要这个字符串将其打印到GUI中的文本框中。



这样的一个例子:

  try:
method_that_can_raise_an_exception(params)
除了异常,e:
print_to_textbox(complete_exception_description(e))
/ pre>

问题是:什么是 complete_exception_description

解决方案

请参阅 traceback 模块,特别是 format_exc )函数。 此处

  import traceback 

try:
raise ValueError
except:
tb = traceback.format_exc()

tb =No error
finally:
print tb


I've seen a lot of posts about stack trace and exceptions in Python. But haven't found what I need.

I have a chunk of Python 2.7 code that may raise an exception. I would like to catch it and assign to a string its full description and the stack trace that caused the error (simply all we use to see on the console). I need this string to print it to a text box in the GUI.

Something like this:

try:
    method_that_can_raise_an_exception(params)
except Exception, e:
    print_to_textbox(complete_exception_description(e))

The problem is: what is the function complete_exception_description?

解决方案

See the traceback module, specifically the format_exc() function. Here.

import traceback

try:
    raise ValueError
except:
    tb = traceback.format_exc()
else:
    tb = "No error"
finally:
    print tb

这篇关于获取引发异常的异常描述和堆栈跟踪,全部为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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