Extracting the traceback

B

billiejoex

Hi there,
I'm facing a case where I need to get the traceback outptut when
occurring an exception.
I solved such problem by using traceback module in conjunction with
StringIO:

import StringIO, traceback
try:
raise Exception
except:
f = StringIO.StringIO()
traceback.print_exc(file=f)
print f.getvalue()

.... but this seems a little poor to me since I first put output into
the StringIO.StringIO(), then I get it back by using getvalue() on
it.
Is there a way to avoid the use of StringIO and get such output
without using such (useless) additional step?

Thanks in advance
 
E

Evan Klitzke

Hi there,
I'm facing a case where I need to get the traceback outptut when
occurring an exception.
I solved such problem by using traceback module in conjunction with
StringIO:

import StringIO, traceback
try:
raise Exception
except:
f = StringIO.StringIO()
traceback.print_exc(file=f)
print f.getvalue()

... but this seems a little poor to me since I first put output into
the StringIO.StringIO(), then I get it back by using getvalue() on
it.
Is there a way to avoid the use of StringIO and get such output
without using such (useless) additional step?

If you just want to print the output (as in your example), you can use
file=sys.stdout or file=sys.stderr in the call to print_exc. If you
want to store the traceback into a string for some other purpose (e.g.
logging, email notifications) I believe that you must use a StringIO
object.
 
C

codesite-noreply

If you just want to print the output (as in your example), you can use
file=sys.stdout or file=sys.stderr in the call to print_exc. If you
want to store the traceback into a string for some other purpose (e.g.
logging, email notifications) I believe that you must use a StringIO
object.

Unfortunately I have to pass the output to a function which prints the
passed string both on screen and into a log file.
Anyway, not too much important. I'll use StringIO if there's no other
solution.

Thanks
 
E

Evan Klitzke

Unfortunately I have to pass the output to a function which prints the
passed string both on screen and into a log file.
Anyway, not too much important. I'll use StringIO if there's no other
solution.

Turns out I was wrong -- you can just get the string, using format_exc
rather than print_exc.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,001
Messages
2,570,254
Members
46,849
Latest member
Fira

Latest Threads

Top