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

新手上路,请多包涵

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

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

是这样的:

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

问题是: 函数 complete_exception_description 是什么?

原文由 bluish 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 340
2 个回答

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

 import traceback

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

原文由 kindall 发布,翻译遵循 CC BY-SA 4.0 许可协议

让我们创建一个相当复杂的堆栈跟踪,以证明我们获得了完整的堆栈跟踪:

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

def do_something_that_might_error():
    raise_error()

记录完整的堆栈跟踪

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

 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!

原文由 Russia Must Remove Putin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题