我希望在不退出的情况下捕获和记录异常,例如,

try:
    do_stuff()
except Exception as err:
    print(Exception, err)
    # I want to print the entire traceback here,
    # not just the exception name and details

我想打印与在不使用try的情况下引发异常时打印的完全相同的输出..除了拦截异常,我希望它退出我的程序.我该怎么做?

推荐答案

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

请注意,有了print_exc,在某些情况下,你将无法获得你所期望的.在Python 2中.x:

import traceback

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

    traceback.print_exc()

...将显示last异常的回溯:

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

If you really need to access the original traceback一种解决方案是将从exc_info返回的exception infos缓存在局部变量中,并使用print_exception显示它:

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!

不过,这方面几乎没有什么缺陷:

  • sys_info号文件:

    将回溯返回值赋给处理异常的函数中的局部变量将导致circular reference.这将防止同一函数中的局部变量或回溯引用的任何内容被垃圾收集.[...] If you do need the traceback, make sure to delete it after use(最好用try…finally语句)

  • 但是,出自同一份文件:

    Beginning with Python 2.2, such cycles are automatically reclaimed当垃圾收集被启用时,它们变得不可访问,但避免创建循环仍然更有效.


另一方面,通过允许您在异常情况下访问回溯associated with,Python3产生了一个不那么令人惊讶的结果:

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!")

Python相关问答推荐

如何调整spaCy token 化器,以便在德国模型中将数字拆分为行末端的点

理解Python的二分库:澄清bisect_left的使用

如何在msgraph.GraphServiceClient上进行身份验证?

沿着数组中的轴计算真实条目

如何找到满足各组口罩条件的第一行?

什么相当于pytorch中的numpy累积ufunc

在Polars(Python库)中将二进制转换为具有非UTF-8字符的字符串变量

如何更改分组条形图中条形图的 colored颜色 ?

为什么以这种方式调用pd.ExcelWriter会创建无效的文件格式或扩展名?

如何在Raspberry Pi上检测USB并使用Python访问它?

如何将多进程池声明为变量并将其导入到另一个Python文件

导入...从...混乱

在单个对象中解析多个Python数据帧

如何在Python中使用另一个数据框更改列值(列表)

如何使用OpenGL使球体遵循Python中的八样路径?

如何从pandas DataFrame中获取. groupby()和. agg()之后的子列?

如何使用pytest在traceback中找到特定的异常

上传文件并使用Panda打开时的Flask 问题

使用xlsxWriter在EXCEL中为数据帧的各行上色

基于2级列表的Pandas 切片3级多索引