我可以得到抛出异常的Python函数的局部变量吗? [英] Can I get the local variables of a Python function from which an exception was thrown?
问题描述
def myfunction():
v1 = get_a_value()
raise异常()
try:
myfunction()
除了:
#我可以从这里访问v1吗?
通常,清洁设计将值传递给异常如果你知道你的异常处理代码将需要它。但是,如果您正在编写一个调试器或类似的调试器,那么您将需要访问变量而不知道它们是哪一个,那么您可以在上下文中访问任意变量抛出:
def myfunction():
v1 = get_a_value()
raise异常()
尝试:
myfunction()
除了:
#我可以从这里访问v1吗?
v1 = inspect.trace()[ - 1] [0] .f_locals ['v1']
描述 trace
函数的功能以及 traceback
对象所处理的对象的格式在 inspect
模块文档。
I'm writing a custom logging system for a project. If a function throws an exception, I want to log its local variables. Is it possible to access the raising function's local variables from the except block that caught the exception? For example:
def myfunction():
v1 = get_a_value()
raise Exception()
try:
myfunction()
except:
# can I access v1 from here?
It's generally cleaner design to pass the value to the exception, if you know that your exception handling code is going to need it. However, if you're writing a debugger or something like that, where you will need to access variables without knowing which ones they are in advance, you can access an arbitrary variable in the context where the exception was thrown:
def myfunction():
v1 = get_a_value()
raise Exception()
try:
myfunction()
except:
# can I access v1 from here?
v1 = inspect.trace()[-1][0].f_locals['v1']
The functionality of the trace
function, and the format of the traceback
objects it deals with, are described in the inspect
module documentation.
这篇关于我可以得到抛出异常的Python函数的局部变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!