Skip to content

Instantly share code, notes, and snippets.

@ieure
Created September 25, 2009 03:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ieure/193277 to your computer and use it in GitHub Desktop.
Save ieure/193277 to your computer and use it in GitHub Desktop.
Context manager to enter the Python debugger when an exception is raised
# -*- coding: utf-8 -*-
#
# Author: Ian Eure <http://github.com/ieure>, <http://atomized.org>
#
"""Enter the debugger on exceptions.
example:
from __future__ import with_statement
from error_debug import debug
with debug():
raise Exception("Just testing")
"""
from contextlib import contextmanager
@contextmanager
def debug(use_pdb=True):
"""When use_pdb is True, enter the debugger if an exception is raised."""
try:
yield
except Exception, e:
if not use_pdb:
raise
import sys
import traceback
import pdb
info = sys.exc_info()
traceback.print_exception(*info)
pdb.post_mortem(info[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment