Is it possible to automatically enter the debugger when an exception is thrown?

If someone catches an exception outside the function in which it was originally thrown, he loses access to the local stack. As a result, you cannot check the values โ€‹โ€‹of variables that could cause an exception.

Is there a way to automatically trigger a break in the debugger ( import pdb; pdb.set_trace() ) whenever import pdb; pdb.set_trace() import pdb; pdb.set_trace() exception for checking local stack?

+10
source share
4 answers

I found what I was looking for in response to What is the easiest way to use pdb pdb to check the cause of an unhandled exception?

Wrap it with this:

 <!-- language: lang-py --> def debug_on(*exceptions): if not exceptions: exceptions = (AssertionError, ) def decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): try: return f(*args, **kwargs) except exceptions: pdb.post_mortem(sys.exc_info()[2]) return wrapper return decorator 

Example:

 @debug_on(TypeError) def buggy_function() .... raise TypeError 
+4
source

You do not want to throw each exception; Python idiomatic code makes heavy use of exceptions (EAFP), so you will constantly break unrelated code.

Use pdb post-mortem instead: import pdb; pdb.pm() import pdb; pdb.pm() . This uses sys.last_traceback to check the stack, including locales at the cast point.

+16
source

ipython supports this ( http://ipython.org ). from inside ipython do

 %pdb on 

and from now on, it will automatically delete you inside the debugger whenever you get an exception.

note that you are likely to get tired of this quickly in general use ... every time you make a mistake and get a syntax error, you have to exit the debugger. but it is sometimes useful.

+12
source

If you want to wrap only some internal part of the function, or if you need to decorate several functions, you can use the context manager as an alternative to the accepted answer. I am currently using this simple version that catches all exceptions. I would also recommend using pudb

 from contextlib import contextmanager @contextmanager def postmortem_pudb(): try: yield except Exception as exc: pudb.post_mortem() 

Use like this

 with postmortem_pudb(): function_that_might_throw_some() ... another_function_that_might_throw_some() ... yet_another_function_that_might_throw_some() 
0
source

All Articles