Possible to capture cgitb style output in a try/except section?
Peter Otten
__peter__ at web.de
Tue Jul 26 10:04:56 EDT 2016
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?
>
> My read of the cgitb documentation leads me to believe that the only way
> I can get cgitb output is to let an exception propagate to the point of
> terminating my script ... at which point cgitb grabs the exception and
> does its magic.
I see Steven has already answered while I was composing an example script.
Rather than throwing it away I'll give it below:
#!/usr/bin/env python3
import cgitb
cgitb.enable()
print("Content-type: text/html\r\n\r\n")
print("<html><body>")
print("hello world<br/>")
for expr in [
"1 + 1",
"1 / 0", # handled in the except clause
"2 * 2",
"1 x 2", # handled by sys.excepthook set via cgitb.enable()
"3 * 3" # not reached
]:
try:
print(expr, "=", eval(expr))
except ZeroDivisionError:
cgitb.Hook().handle()
print("<br/>")
print("</body></html>")
More information about the Python-list
mailing list