Reputation: 2646
Suppose I have a python program where assert has been used to define how things should be, and I would like to capture anomalies with the read-eval-loop rather than having AssertionError
be thrown.
Granted, I could have
if (reality!=expectation):
print("assertion failed");
import pdb; pdb.set_trace();
but that's far more ugly in the code than a plain assert(reality==expectation)
.
I could have pdb.set_trace()
called in an except:
block at top-level, but then I'd have lost all the context of the failure, right ? (I mean, stacktrace could be recovered from the exception object, but not argument values, etc.)
Is there anything like a --magic
command-line flag that could turn the python3 interpreter into what I need ?
Upvotes: 14
Views: 5145
Reputation: 35039
Mainly taken from this great snippet:
import sys
def info(type, value, tb):
if hasattr(sys, 'ps1') or not sys.stderr.isatty() or type != AssertionError:
# we are in interactive mode or we don't have a tty-like
# device, so we call the default hook
sys.__excepthook__(type, value, tb)
else:
import traceback, pdb
# we are NOT in interactive mode, print the exception...
traceback.print_exception(type, value, tb)
print
# ...then start the debugger in post-mortem mode.
pdb.pm()
sys.excepthook = info
When you initialize your code with this, all AssertionError
s should invoke pdb.
Upvotes: 15
Reputation: 1952
Have a look at the nose project. You can use it with the --pdb option to drop into the debugger on errors.
Upvotes: 5