如何在不停止程序的情况下打印完整的回溯?

2024-04-19 19:39:38 发布

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

我正在编写一个程序,可以解析10个网站,定位数据文件,保存文件,然后解析它们,生成可以在NumPy库中随时使用的数据。这个文件通过错误的链接、格式错误的XML、丢失的条目和其他我还没有分类的东西而遇到的错误有很多。我最初制作这个程序是为了处理如下错误:

try:
    do_stuff()
except:
    pass

但现在我想记录错误:

try:
    do_stuff()
except Exception, err:
    print Exception, err

注意:这将打印到日志文件以供以后查看。这通常会打印非常无用的数据。我想要的是打印错误触发时打印的完全相同的行,除了截取异常之外不进行尝试,但我不希望它停止我的程序,因为它嵌套在一系列for循环中,我希望看到这些循环完成。


Tags: 文件数据定位程序numpy网站链接数据文件
3条回答

^{}^{}将产生更多信息,如果这是你想要的。

import traceback
import sys

try:
    do_stuff()
except Exception:
    print(traceback.format_exc())
    # or
    print(sys.exc_info()[2])

如果正在调试并只想查看当前堆栈跟踪,可以简单地调用:

^{}

不需要手动引发异常来再次捕获它。

其他一些答案已经指出了traceback模块。

请注意,使用print_exc,在某些情况下,您将无法获得预期的结果。在Python 2.x中:

import traceback

try:
    raise TypeError("Oups!")
except Exception, err:
    try:
        raise TypeError("Again !?!")
    except:
        pass

    traceback.print_exc()

…将显示上次异常的回溯:

Traceback (most recent call last):
  File "e.py", line 7, in <module>
    raise TypeError("Again !?!")
TypeError: Again !?!

如果您真的需要访问原始的回溯一种解决方案是将从^{}返回的异常信息缓存到一个局部变量中,并使用^{}显示它:

import traceback
import sys

try:
    raise TypeError("Oups!")
except Exception, err:
    try:
        exc_info = sys.exc_info()

        # do you usefull stuff here
        # (potentially raising an exception)
        try:
            raise TypeError("Again !?!")
        except:
            pass
        # end of useful stuff


    finally:
        # Display the *original* exception
        traceback.print_exception(*exc_info)
        del exc_info

生产:

Traceback (most recent call last):
  File "t.py", line 6, in <module>
    raise TypeError("Oups!")
TypeError: Oups!

不过,这方面的陷阱并不多:

  • 来自^{}的文档:

    Assigning the traceback return value to a local variable in a function that is handling an exception will cause a circular reference. This will prevent anything referenced by a local variable in the same function or by the traceback from being garbage collected. [...] If you do need the traceback, make sure to delete it after use (best done with a try ... finally statement)

  • 但是,来自同一个医生:

    Beginning with Python 2.2, such cycles are automatically reclaimed when garbage collection is enabled and they become unreachable, but it remains more efficient to avoid creating cycles.


另一方面,通过允许您访问与异常相关联的回溯,Python 3产生了一个不那么令人惊讶的结果:

import traceback

try:
    raise TypeError("Oups!")
except Exception as err:
    try:
        raise TypeError("Again !?!")
    except:
        pass

    traceback.print_tb(err.__traceback__)

。。。将显示:

  File "e3.py", line 4, in <module>
    raise TypeError("Oups!")

相关问题 更多 >