Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically switch to debug mode on a warning?

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?

like image 634
kjo Avatar asked Dec 21 '15 18:12

kjo


1 Answers

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:

  • Replace the execfile() call with the Python 3 variant; and
  • Replace __builtin__ with builtins.
like image 78
blueogive Avatar answered Oct 12 '22 19:10

blueogive