不知道這是否是你所需要的,但這些可能是你可以打印回溯的方式:
import traceback
try:
s += 1 #this doesnt exist yet
except:
a = traceback.format_exc()
print a
- 或 -
import traceback, sys
def DummyFunc2():
s += 1 #this doesnt exist yet
def DummyFunc1():
DummyFunc2()
try:
DummyFunc1()
except:
_, err, tb = sys.exc_info()
tb_lines = traceback.extract_tb(tb)
for idx, trace in enumerate(traceback.format_list(tb_lines)):
print "[INDEX %d]\n%s" % (idx,trace)
print err
輸出:
>>>
[INDEX 0]
File "C:/Python27/Lib/site-packages/xy/printtrace.py", line 9, in <module>
DummyFunc1()
[INDEX 1]
File "C:/Python27/Lib/site-packages/xy/printtrace.py", line 6, in DummyFunc1
DummyFunc2()
[INDEX 2]
File "C:/Python27/Lib/site-packages/xy/printtrace.py", line 4, in DummyFunc2
s += 1 #this doesnt exist yet
local variable 's' referenced before assignment
>>>
恥辱包在我身上。一切都好 – ardabro