如果在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可以提供什么! –