handy stacktrace class

Discussion in 'Python' started by Will Ware, Dec 12, 2004.

  1. Will Ware

    Will Ware Guest

    I was fooling with some Python code, and starting to miss the
    Exception.printStackTrace() feature in Java. Here is a stab at
    something roughly analogous, which puts together a stacktrace
    as an XML document.

    import xml.dom.minidom

    class Stacktrace(xml.dom.minidom.Document):
    def __init__(self):
    import sys
    xml.dom.minidom.Document.__init__(self)
    stacktrace = self.createElement("stacktrace")
    self.appendChild(stacktrace)
    try:
    raise Exception
    except:
    tb = sys.exc_traceback
    x = tb.tb_frame.f_back
    while x != None:
    f = x.f_code
    frame = self.createElement("frame")
    frame.setAttribute("func", f.co_name)
    frame.setAttribute("file", f.co_filename)
    frame.setAttribute("line", repr(f.co_firstlineno))
    stacktrace.appendChild(frame)
    x = x.f_back
    def __repr__(self):
    import xml.dom.ext
    class MyStream:
    def __init__(self):
    self.str = ""
    def write(self, x):
    self.str += x
    stream = MyStream()
    xml.dom.ext.PrettyPrint(self, stream)
    return stream.str[:-1] # trim trailing newline

    The rational for doing this as an XML document was, uh, gee, I
    thought I had a good reason at the time. I think I've seen XML
    sequences of stacktraces elsewhere and it looked like a good idea.
    My brief time of muddling about with xml.dom.minidom makes me
    think that elements are inherently tied to a particular document
    and can't just be lifted and moved to another document, as one
    might want to do to, say, build a sequence of stacktraces while
    debugging something. But I'm sure there's some kind of workaround
    for that.
     
    Will Ware, Dec 12, 2004
    #1
    1. Advertising

  2. Will Ware wrote:

    >I was fooling with some Python code, and starting to miss the
    > Exception.printStackTrace() feature in Java.


    traceback.print_exc()

    </F>
     
    Fredrik Lundh, Dec 12, 2004
    #2
    1. Advertising

  3. Will Ware

    Guest

    Oh. Never mind, then.
     
    , Dec 13, 2004
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. darrel
    Replies:
    1
    Views:
    400
    darrel
    Mar 29, 2005
  2. Torsten Schmeissel
    Replies:
    0
    Views:
    424
    Torsten Schmeissel
    Apr 29, 2005
  3. Replies:
    0
    Views:
    281
  4. fuzzylollipop
    Replies:
    1
    Views:
    440
    Simon Forman
    Aug 17, 2006
  5. Tim Williams
    Replies:
    0
    Views:
    363
    Tim Williams
    Aug 17, 2006
Loading...

Share This Page