其他一些答案已经指出了追溯模块。
请注意,使用
print_exc,在某些特殊情况下,你将无法获得预期的结果。在Python 2.x中:
import tracebacktry: 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 tracebackimport systry: 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:
在处理异常的函数中将回溯返回值分配给局部变量将导致循环引用。这将防止垃圾回收由同一函数中的局部变量或回溯引用的任何内容。[…] 如果确实需要回溯,请确保在使用后将其删除(最好通过try … finally语句完成)
但是,根据同一文档:
从Python 2.2开始,启用垃圾回收并且无法访问时,会自动回收此类循环,但是避免创建循环仍然更加有效。
另一方面,通过允许你访问与异常关联的回溯,Python 3产生了一个不太令人惊讶的结果:
import tracebacktry: raise TypeError("Oups!")except Exception as err: try: raise TypeError("Again !?!") except: passtraceback.print_tb(err.__traceback__)
…将显示:
File "e3.py", line 4, in <module> raise TypeError("Oups!")


