How to check the scope of a function in which Python throws an exception?

I recently discovered a very useful -i flag for Python

  -i: inspect interactively after running script, (also PYTHONINSPECT = x)
          and force prompts, even if stdin does not appear to be a terminal

This is great for checking objects in a global scope, but what happens if an exception was thrown in a function call, and I would like to check the local variables of the function? Naturally, I am interested in the area in which the exception was first raised, is there any way to get to it?

+1
source share
3 answers

At the online prompt, type

>>> import pdb >>> pdb.pm() 

pdb.pm () - post-mortem debugger. It will put you in the area where the exception was thrown, and then you can use the usual pdb commands.

I use it all the time. This is part of the standard library (ipython is not necessary) and does not require editing debug commands in the source code.

The only trick - do not forget to do it right away; if you enter any other commands, you will lose the area in which the exception occurred.

+5
source

In ipython, you can check variables in the place where your code crashed without the need to change it:

 >>> %pdb on >>> %run my_script.py 
+5
source

use ipython: http://mail.scipy.org/pipermail/ipython-user/2007-January/003985.html

Usage example:

 from IPython.Debugger import Tracer; debug_here = Tracer() #... later in your code debug_here() # -> will open up the debugger at that point. 

"Once the debugger is activated, you can use all your regular commands for step-by-step code, set breakpoints, etc. See the pdb documentation from the Python standard library for usage details."

+4
source

Source: https://habr.com/ru/post/1437374/


All Articles