其他一些答案已经指出了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!")