剛才順著 django-debug-toolbar 的程式一路往下追, 看到它用 traceback.extract_stack() 取出 call stack, 於是就看了一下這函式的內容:
def extract_stack(f=None, limit = None):
# ... 中略 ...
if f is None:
try:
raise ZeroDivisionError
except ZeroDivisionError:
f = sys.exc_info()[2].tb_frame.f_back
# ... 中略 ...
while f is not None and (limit is None or n < limit):
lineno = f.f_lineno
# ... 中略 ...
list.append((filename, lineno, name, line))
f = f.f_back
n = n+1
list.reverse()
return list
自己丟 Exception 再抓回取出 call stack, 這作法真是太妙了, 相當地簡單易懂。
沒有留言:
張貼留言