Skip to content

Instantly share code, notes, and snippets.

@mikepfirrmann
Created September 24, 2012 15:23
Show Gist options
  • Save mikepfirrmann/3776509 to your computer and use it in GitHub Desktop.
Save mikepfirrmann/3776509 to your computer and use it in GitHub Desktop.
Print a prettier stack trace for Python exceptions
try:
# put whatever code here
except:
import traceback, StringIO, re, os
def colorize(text, color):
control_sequence_introducer = "\x1B["
return "{0}{1}m{2}{0}0m".format(control_sequence_introducer, color, text)
exception_output = StringIO.StringIO()
traceback.print_exc(file=exception_output)
stack_trace = exception_output.getvalue().splitlines()
stack_trace.pop(0)
error = stack_trace.pop()
print ''
i = 0
for line in stack_trace:
line = line.strip()
if 0 == i % 2:
matches = re.match('File "(.*)", line (\d+), in (.+)', line)
if matches:
groups = matches.groups()
path = groups[0]
path = path.replace(os.getcwd(), '')
line_number = groups[1]
method = groups[2]
else:
print "{0} ({1}): {2}: {3}".format(
colorize(path, 36),
colorize(line_number, 33),
colorize(method, 32),
colorize(line, 31)
)
i = i + 1
print colorize("Error ", 33) + colorize(error, 31)
print ''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment