Python プログラムでバグが検出された場合、スタック トレースの他に、グローバル変数とローカル変数を含むコンテキスト ダンプを生成すると便利です。
例外ハンドラーがグローバルとローカルにアクセスできる方法はありますか?
以下のコード例:
# 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)
...