Catching error text like that shown in console?

Kent Johnson kent at kentsjohnson.com
Fri Dec 9 20:37:47 EST 2005


Peter A. Schott wrote:
> I know there's got to be an easy way to do this - I want a way to catch the
> error text that would normally be shown in an interactive session and put that
> value into a string I can use later.  I've tried just using a catch statement
> and trying to convert the output to string, but this doesn't always work.  I
> really don't have programs complex enough to do a lot of specific catching at
> this point - I just want to know:
>   1. something failed
>   2. here's the error output/traceback

If you just want to catch exceptions and print a traceback, use the 
traceback module. This is handy for example if you are processing a 
number of items and don't want a failure in one to abort the whole loop:

import traceback
for work in thingsToDo:
   try:
     doSomeWork(work)
   except:
     traceback.print_exc()

If you want more control over the exception info - for example to put it 
in a string instead of printing it - look at the other functions in the 
traceback module.

Kent



More information about the Python-list mailing list