如果在 Python 程序中检测到错误,则在堆栈跟踪旁边生成包含全局变量和局部变量的上下文转储将很有用。
异常处理程序是否可以通过某种方式访问全局变量和局部变量,而不必在引发异常语句中包含 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)
...