Skip to content

Instantly share code, notes, and snippets.

@redliu312
Forked from ieure/error_debug.py
Created December 22, 2017 20:43
Show Gist options
  • Save redliu312/09ade1f0e228a3a4c7b8a2a36cc836aa to your computer and use it in GitHub Desktop.
Save redliu312/09ade1f0e228a3a4c7b8a2a36cc836aa 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