如果在Python程序中檢測到錯誤,除了堆棧跟蹤之外,生成上下文轉儲(包括全局變量和局部變量)將非常有用。異常處理程序可以在異常引發下訪問全局變量和局部變量嗎?
是否有某種方式讓異常處理程序可以訪問全局和本地,而不必在raise異常語句中包含globals()和locals()?
實施例以下代碼:
# Python 3.3 code
import sys
class FunError(Exception):
pass
def fun(x): # a can't be 2 or 4
if x in [2, 4]:
raise FunError('Invalid value of "x" variable')
else:
return(x ** 2)
try:
print(fun(4))
except Exception as exc:
# Is value of 'x' variable at time of exception accessible here ?
sys.exit(exc)
所得的答案上的異常代碼:
...
except FunError as exc:
tb = sys.exc_info()[2] # Traceback of current exception
while tb.tb_next: # Dig to end of stack
tb = tb.tb_next # Next level
print('Local at raise exception: x =', tb.tb_frame.f_locals['x']) # Wanted data
sys.exit(exc)
...
也感謝您參考其他文檔。真的讓人驚訝,Python可以提供什麼! –