ANN: grassi python 3.0

Tim Peters tim_one at email.msn.com
Wed Dec 8 02:45:58 EST 1999


[t. muddletyn]
> ...
> If you shove the following at the top of your perl CGI ....
>
>     use CGI::Carp qw(fatalsToBrowser);
>
> ... It does indeed dump syntax/compile errors to the browser
> (ie. prints the content type and a minimal HTML file reporting
> the syntax (or whatever) error).
>
>     use CGI::Carp qw(fatalsToBrowser);
>     print 1/0;
>
> will spit out...
>
> --snip--
> Content-type: text/html
>
> <H1>Software error:</H1>
> <CODE>Illegal division by zero at ./test.cgi line 4.
> </CODE>
> <P>
> Please send mail to this site's webmaster for help.
> [Mon Dec  6 03:21:03 1999] test.cgi: Illegal division by zero at
> ./test.cgi line 4.
> --unsnip--
> ...
> Anyhow, i have long wondered if, besides the exception wrapper
> hacks we've seen in these threads (and i use one of my own
> devising myself), is it possible to somehow hack python ... to
> operate similar to the above CGI::Carp hack?

Not really.  The Perl gimmick relies on Perl's $SIG[__DIE__] hook (a
user-settable callback function invoked prior to a fatal error).  Python
doesn't have that hook; by using try/except, you're essentially building
such a hook by hand.

I fail to see why try/except would be thought insufficient in this case.  If
someone is terminally lazy <wink>, they might consider importing this module
(call it, say, fatalsToBrowser.py):

import StringIO
import sys

def report():
    guts = file.getvalue()
    if not guts:
        return
    sys.__stderr__.write(guts)  # to the server log
    guts = "Whoopee!!  An error!\n" + guts  # etc
    sys.stdout.write(guts)      # to the browser

file = StringIO.StringIO()
sys.stderr = file
sys.exitfunc = report

This arranges to redirect all stderr output to a StringIO object, and to
call report() when the interpreter exits (except in case of death in
response to a signal, fatal internal interpreter error, or os._exit()).
report() can then look at everything (if anything) that was sent to stderr,
reformat it any way it likes, and print it to stdout instead (or throw it
away, or import a Perl module and let CGI::Carp handle it <wink>).

vaults-of-despair-ly y'rs  - tim







More information about the Python-list mailing list