Possible to capture cgitb style output in a try/except section?

Steven D'Aprano steve at pearwood.info
Tue Jul 26 09:40:27 EDT 2016


On Tue, 26 Jul 2016 08:11 pm, Malcolm Greene wrote:

> Is there a way to capture cgitb's extensive output in an except clause
> so that cgitb's detailed traceback output can be logged *and* the except
> section can handle the exception so the script can continue running?

Anything that cgitb captures in a traceback can be captured at any time and
processed anyway you like. There's no real magic happening in cgitb, you
can read the source and program your own traceback handler that records any
details you like.

Or you can use the cgitb module as-is, and capture the output:


py> from StringIO import StringIO
py> s = StringIO()
py> import cgitb
py> handler = cgitb.Hook(file=s, format="text").handle
py> try:
...     x = 1/0
... except Exception as e:
...     handler()
...
py> text = s.getvalue()
py> print text
<type 'exceptions.ZeroDivisionError'>
Python 2.7.2: /usr/local/bin/python2.7
Tue Jul 26 23:37:06 2016

A problem occurred in a Python script.  Here is the sequence of
function calls leading up to the error, in the order they occurred.

[...]

The above is a description of an error in a Python program.  Here is
the original traceback:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero




-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list