Can I get the local variables of a Python function from which an exception was thrown?

后端 未结 6 770
时光说笑
时光说笑 2020-12-08 00:54

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

6条回答
  •  离开以前
    2020-12-08 01:49

    You can look up the local variables in the frame object, which you can get from sys.exc_info.

    >>> import sys
    >>> def f(a):
    ...     b = a - 1
    ...     print 1.0 / b
    ...
    >>> try:
    ...     f(1)
    ... except Exception, e:
    ...     print sys.exc_info()[2].tb_next.tb_frame.f_locals
    ...
    {'a': 1, 'b': 0}
    

    You'll have to include the appropriate number of tb_nexts depending on from how deep in the stack the exception was thrown.

提交回复
热议问题