nested exceptions dilemma
Chris Liechti
cliechti at gmx.net
Fri Jan 4 17:41:49 EST 2002
"Jason R. Mastaler" <jason-dated-1010870388.8e8b05 at mastaler.com> wrote in
news:mailman.1010179207.14938.python-list at python.org:
> Greetings,
>
> I'm trying to write a "wrapper" script whose purpose is to execute a
> more complex Python script, catch all exceptions that it might
> generate, and then log the corresponding tracebacks.
>
> It should first try to log to file ~/tmda.debug. If any exceptions
> occur while trying that, it attempts to instead log to
> ~/CATASTROPHIC_FAILURE. If any exceptions occur while trying that,
> the script prints the traceback to stdout before giving up.
>
> Here is a simplified example of the wrapper:
>
> ---- start ----
>
> #!/usr/bin/env python
> try:
> import os
> import sys
> import traceback
> execfile('tmda-filter')
> except:
> try:
> fp = open(os.path.expanduser('~/tmda.debug'))
> traceback.print_exc(file=fp)
> except:
> try:
> fp = open(os.path.expanduser('~/CATASTROPHIC_FAILURE'))
> traceback.print_exc(file=fp)
> except:
> traceback.print_exc(file=sys.stdout)
>
> ---- end ----
>
> The problem I'm having is that traceback.print_exc only prints the
> traceback from the most recently raised exception. For example, if
> the write to "~/tmda.debug" raises an IOError exception, the traceback
> that ends up in ~/CATASTROPHIC_FAILURE only shows that and has no
> mention of why the execfile failed.
>
> Instead, I'd like to include the entire chain of exceptions in the
> traceback. Does anyone have any suggestions on how to accomplish
> this?
you could save the traceback (sys.exc_info()) and evaluate it later
or use StringIO at the beginning of your exception handling:
exf = StringIO
traceback.print_exc(file=exf)
and then below open the file etc... and use fp.write(fp.getvalue())
> Thanks.
>
--
Chris <cliechti at gmx.net>
More information about the Python-list
mailing list