获取导致异常的异常描述和堆栈跟踪,全部为字符串

2024-03-28 22:20:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我看过很多关于Python中堆栈跟踪和异常的文章。但还没有找到我需要的。

我有一段Python2.7代码可能会引发异常。我想捕获它并将其完整描述和导致错误的堆栈跟踪(只是我们在控制台上看到的所有内容)分配给一个字符串。我需要这个字符串将其打印到GUI中的文本框中。

像这样的:

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

问题是:什么是函数complete_exception_description


Tags: 字符串代码内容that堆栈错误文章exception
3条回答

使用Python 3,以下代码将格式化一个Exception对象,与使用traceback.format_exc()获得的完全一样:

import traceback

try: 
    method_that_can_raise_an_exception(params)
except Exception as ex:
    print(''.join(traceback.format_exception(etype=type(ex), value=ex, tb=ex.__traceback__)))

其优点是只需要Exception对象(由于记录了__traceback__属性),因此可以更容易地作为参数传递给另一个函数进行进一步处理。

让我们创建一个非常复杂的stacktrace,以演示我们得到了完整的stacktrace:

def raise_error():
    raise RuntimeError('something bad happened!')

def do_something_that_might_error():
    raise_error()

记录完整的stacktrace

最佳实践是为模块设置记录器。它将知道模块的名称并能够更改级别(以及其他属性,如处理程序)

import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

我们可以使用此记录器获取错误:

try:
    do_something_that_might_error()
except Exception as error:
    logger.exception(error)

哪些日志:

ERROR:__main__:something bad happened!
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 2, in do_something_that_might_error
  File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!

因此,我们得到的输出与出现错误时相同:

>>> do_something_that_might_error()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in do_something_that_might_error
  File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!

只得到绳子

如果您真的只需要字符串,请改用traceback.format_exc函数,演示如何在此处记录字符串:

import traceback
try:
    do_something_that_might_error()
except Exception as error:
    just_the_string = traceback.format_exc()
    logger.debug(just_the_string)

哪些日志:

DEBUG:__main__:Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 2, in do_something_that_might_error
  File "<stdin>", line 2, in raise_error
RuntimeError: something bad happened!

请参阅traceback模块,特别是format_exc()函数。Here

import traceback

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

相关问题 更多 >