输入到 excepthook 方法的回溯对象没有文档中列出的任何属性或属性,因此它显然是“回溯对象”的不同形式。
我没有看到:
import sys
import traceback
def myhandler(e_class, e_instance, tb_obj):
print "hello**************\n"
print e_instance
traceback.print_tb(tb_obj)
print
while tb_obj:
frame = tb_obj.tb_frame
print 'locals --->', frame.f_locals
print 'globals -->', frame.f_globals, "\n"
tb_obj = tb_obj.tb_next
print "goodbye************"
sys.excepthook = myhandler
x = 10
def do_stuff():
y = 20
def inner():
z = 30
1/0
inner()
do_stuff()
--output:--
hello**************
integer division or modulo by zero
File "1.py", line 32, in <module>
do_stuff()
File "1.py", line 30, in do_stuff
inner()
File "1.py", line 28, in inner
1/0
locals ---> {'__builtins__': <module '__builtin__' (built-in)>, '__file__': '1.py', 'traceback': <module 'traceback' from '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/traceback.pyc'>, '__package__': None, 'sys': <module 'sys' (built-in)>, 'x': 10, '__name__': '__main__', 'do_stuff': <function do_stuff at 0x2b33f0>, '__doc__': None, 'myhandler': <function myhandler at 0x2b3430>}
globals --> {'__builtins__': <module '__builtin__' (built-in)>, '__file__': '1.py', 'traceback': <module 'traceback' from '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/traceback.pyc'>, '__package__': None, 'sys': <module 'sys' (built-in)>, 'x': 10, '__name__': '__main__', 'do_stuff': <function do_stuff at 0x2b33f0>, '__doc__': None, 'myhandler': <function myhandler at 0x2b3430>}
locals ---> {'y': 20, 'inner': <function inner at 0x2b33b0>}
globals --> {'__builtins__': <module '__builtin__' (built-in)>, '__file__': '1.py', 'traceback': <module 'traceback' from '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/traceback.pyc'>, '__package__': None, 'sys': <module 'sys' (built-in)>, 'x': 10, '__name__': '__main__', 'do_stuff': <function do_stuff at 0x2b33f0>, '__doc__': None, 'myhandler': <function myhandler at 0x2b3430>}
locals ---> {'z': 30}
globals --> {'__builtins__': <module '__builtin__' (built-in)>, '__file__': '1.py', 'traceback': <module 'traceback' from '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/traceback.pyc'>, '__package__': None, 'sys': <module 'sys' (built-in)>, 'x': 10, '__name__': '__main__', 'do_stuff': <function do_stuff at 0x2b33f0>, '__doc__': None, 'myhandler': <function myhandler at 0x2b3430>}
goodbye************
我已经阅读了一些关于回溯模块的信息,但老实说对我来说没有多大意义
回溯模块与回溯对象不同。两人只是碰巧同名而已。在 sys.excepthook() 函数中,如果将参数命名为 variable traceback
,不要期望它具有 traceback 模块中列出的任何方法。以下是回溯对象的属性:
http://docs.python.org/2/reference/datamodel.html