Source

hotdebug / codebase.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set ai et si ts=4 sts=4 sw=4:

from itertools import izip, islice
import linecache


def get_file_part(filename, lineno, lines_around, g=None):

    linecache.checkcache(filename)
    lines = linecache.getlines(filename, g)
    line = linecache.getline(filename, lineno, g)
    if not lines:
        return [(lineno, line)]

    b, e = lineno - lines_around - 1, lineno + lines_around
    if b < 0:
        b = 0
    if e > len(lines):
        e = len(lines)

    return [(ln, l) for ln, l in izip(
        xrange(b + 1, e + 1), islice(lines, b, e))]


def iter_tracback(tb, lines_around=7):
    depth = 1

    # skip the first
    tb = tb.tb_next

    while tb is not None:
        f = tb.tb_frame
        co = f.f_code
        filename = co.co_filename
        lineno = tb.tb_lineno
        where = co.co_name
        lines = get_file_part(filename, lineno, lines_around, f.f_globals)
        yield depth, filename, where, lineno, lines, f.f_locals

        tb = tb.tb_next
        depth += 1