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

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/,只是拦截异常,并且我不希望它退出程序。


当前回答

如果你已经有了一个Error对象,并且你想打印整个东西,你需要做这个有点尴尬的调用:

import traceback
traceback.print_exception(type(err), err, err.__traceback__)

没错,print_exception接受三个位置参数:异常的类型、实际的异常对象和异常自身的内部回溯属性。

在python 3.5或更高版本中,类型(err)是可选的…但它是一个位置参数,所以你仍然需要显式地在它的位置传递None。

traceback.print_exception(None, err, err.__traceback__)

我不知道为什么所有这些不只是traceback.print_exception(err)。为什么你会想打印出一个错误,以及一个回溯,而不是属于该错误的,这超出了我的理解。

其他回答

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

traceback.print_stack ()

没有必要为了再次捕获异常而手动引发异常。

关于这个答案的注释:print(traceback.format_exc())对我来说比traceback.print_exc()更好。对于后者,hello有时会奇怪地与回溯文本“混合”在一起,比如两者都想同时写入stdout或stderr,产生奇怪的输出(至少在从文本编辑器内部构建并在“构建结果”面板中查看输出时)。

回溯(最近一次调用): 文件“C:\Users\User\Desktop\test.py”,第7行,在 地狱do_stuff () 文件“C:\Users\User\Desktop\test.py”,第4行,do_stuff 1/0 ZeroDivisionError:整数除法或对0取模 o [0.1s完成]

所以我用:

import traceback, sys

def do_stuff():
    1/0

try:
    do_stuff()
except Exception:
    print(traceback.format_exc())
    print('hello')

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

请注意,使用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 !?!

如果你真的需要访问原始的回溯,一个解决方案是将exc_info返回的异常信息缓存到一个局部变量中,并使用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!

但这也有一些陷阱:

From the doc of sys_info: 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) but, from the same doc: 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!")

Traceback.format_exc()或sys.exc_info()将产生更多信息,如果这是你想要的。

import traceback
import sys

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

traceback.format_exception (exception_object)

如果你只有异常对象,你可以从Python 3中的任何代码点获得字符串形式的回溯:

import traceback

''.join(traceback.format_exception(None, exc_obj, exc_obj.__traceback__))

完整的例子:

#!/usr/bin/env python3

import traceback

def f():
    g()

def g():
    raise Exception('asdf')

try:
    g()
except Exception as e:
    exc_obj = e

tb_str = ''.join(traceback.format_exception(None, exc_obj, exc_obj.__traceback__))
print(tb_str)

输出:

Traceback (most recent call last):
  File "./main.py", line 12, in <module>
    g()
  File "./main.py", line 9, in g
    raise Exception('asdf')
Exception: asdf

文档:https://docs.python.org/3.9/library/traceback.html traceback.format_exception

请参见:从异常对象中提取回溯信息

在Python 3.9中测试