returning traceback strings
holger krekel
pyth at devel.trillke.net
Thu Jun 13 18:38:53 EDT 2002
Matthew Boedicker wrote:
> Hello,
>
> I am looking for something exactly like traceback.print_exc(), but instead
> of writing the traceback text to a filehandle, I want it to return it to
> me as a string. I was unable to find any way to do this using the traceback
> module, since everything there seems to be in terms of file handles being
> passed around.
>
> The problem is I need to pass the entire multi-line traceback string to a
> file-like object's write() method in one call, not line by line.
>
> This is the best workaround I was able to come up with:
>
> import cStringIO
> import traceback
>
> def print_exc_str():
> buf = cStringIO.StringIO()
> traceback.print_exc(file=buf)
> return buf.getvalue()
this is a straightforward solution. if you don't want
cStringIO you could do:
import traceback
class fakefile(list):
write=list.append
def get_exception():
ff=fakefile()
traceback.print_exc(file=ff)
return "\n".join(ff)
> Any suggestions for a better way? What about the traceback module using
> strings internally, and wrapping another layer around that to write to files
> and file-like objects?
The traceback module seems to route every print through '_print' (look
into traceback.py) but you can't just replace 'file' with a string,
because strings are immutable. You have to use a mutable type
like a list <wink>.
holger
More information about the Python-list
mailing list