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 ?
To start the debugger from the Python interactive console, we are using run() or runeval(). To continue debugging, enter continue after the ( Pdb ) prompt and press Enter. If you want to know the options we can use in this, then after the ( Pdb ) prompt press the Tab key twice.
Using the -O flag (capital O) disables all assert statements in a process.
Basic debugging# If you're only interested in debugging a Python script, the simplest way is to select the down-arrow next to the run button on the editor and select Debug Python File in Terminal.
If an assertion fails, then your program should crash because a condition that was supposed to be true became false. You shouldn't change this intended behavior by catching the exception with a try … except block. A proper use of assertions is to inform developers about unrecoverable errors in a program.
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.
Have a look at the nose project. You can use it with the --pdb option to drop into the debugger on errors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With