February 28, 2014 · python

pause on exception in python

Pause on exception allow you to inspect variables and stack, quite useful. The default behavior in python is to sys.exit when an exception propagate up the stack.

To pause on exception, save this file as debug.py


    import sys
    
    def info(type, value, tb):
        if hasattr(sys, 'ps1') or not sys.stderr.isatty():
        # 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() # deprecated
            pdb.post_mortem(tb) # more 'modern'
    
    sys.excepthook = info

and import this file in python script.

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket