W
Will Ware
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.
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.