I want to debug a warning that occurs well into the code's execution.
A simple breakpoint won't do, because the line that results in the warning executes millions of times without warning before the first warning occurs.
Also, the line where this is happening is in library code (more precisely, in pandas/core/common.py
), so my preference is not to modify the code at all.
I just want to stop the program's execution right when it emits the warning, and inspect the stack at this point, either with pdb
or with ipdb
.
Is there a way to configure either debugger to automatically enter single-step mode upon the issuing of a warning?
I found the answer offered by @user2683246 elegant and useful. Here is a variant of the solution modified for compatibility with Python3 (tested with Python 3.7):
#!/usr/bin/env python
import pdb, warnings, sys
import builtins
if __name__ == '__main__':
args, n = [], len(sys.argv)
if n < 2:
sys.exit(1)
elif n > 2:
args.append(builtins.__dict__[sys.argv[2]])
if n > 3:
args.append(int(sys.argv[3]))
warnings.simplefilter('error', *args) # treat warnings as exceptions
try:
with open(sys.argv[1]) as f:
code = compile(f.read(), sys.argv[1], 'exec')
exec(code)
except:
pdb.post_mortem(sys.exc_info()[-1])
Notable changes:
execfile()
call with the Python 3 variant; and__builtin__
with builtins
.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