我可以得到抛出异常的Python函数的局部变量吗? [英] Can I get the local variables of a Python function from which an exception was thrown?

查看:142
本文介绍了我可以得到抛出异常的Python函数的局部变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为项目编写自定义日志记录系统。如果一个函数抛出一个异常,我想记录它的局部变量。是否可以从捕获异常的except块访问raise函数的局部变量?例如:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆