Getting terse tracebacks?

skip at skip at
Sun Jan 1 22:50:22 EST 2006

    Roy> Is there any way to make the traceback printer built into the
    Roy> interpreter elide all the directories in pathnames (like
    Roy> strip_dirs() does for the profiler)?

There's a compact traceback printer in asyncore (compact_traceback).  I used
it as the basis for a compact stack printer:

    import os
    import sys

    # adapted from asyncore.compact_traceback()
    def compact_stack(start=0, size=100):
        """build a compact stack trace from frame start to end"""
        f = sys._getframe(start+1)          # don't include this frame
        info = []
        while f:
            fn = os.path.normpath(os.path.abspath(f.f_code.co_filename))
            info.append((fn, f.f_code.co_name, f.f_lineno))
            f = f.f_back

        # eliminate any common prefix the filenames share
        info = [(f.split(os.sep)[-1], c, l) for (f, c, l) in info]

        return '\n'.join(['[%s|%s|%d]' % x for x in info[:size]])

    def print_compact_stack(f=sys.stderr, start=0, size=100):
        print >> f, compact_stack(start+1, size)


More information about the Python-list mailing list