How can I extract local variables from a stack trace?

前端 未结 3 1209
深忆病人
深忆病人 2021-01-05 01:22

Suppose I have a function that raises unexpected exceptions, so I wrap it in ipdb:

def boom(x, y):
    try:
        x / y
    except Exception as e:
                 


        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-05 01:52

    Depending on what you need, there are 2 general best practices.

    Just print the variables with minimal code edits

    Have a look at some related packages. For simple usage you might pick traceback-with-variables (pip install traceback-with-variables), here is it's postcard

    Or try tbvaccine, or better-exceptions, or any other package

    Programmatically access variables to use them in your code

    Use inspect module

    except ... as ...:
        x = inspect.trace()[-1][0].f_locals['x']
    

    What about debugger?

    Debugger is made for step-by-step execution and breakpoints. Using it to inspect exception reasons is really inconvenient and should be avoided. You can automate your debug session using two mentioned best practices.

提交回复
热议问题