redirecting stderr

Peter Otten __peter__ at web.de
Thu Nov 25 08:25:47 EST 2004


Michele Simionato wrote:

> Maybe it is something obvious, but what is going on with this code?
> 
> import sys
> myerr = file("myerr.txt", "w")
> sys.stderr = myerr
> try:
>     raise Exception, "some error"
> finally:
>     myerr.close()
>     sys.stderr = sys.__stderr__
> 
> I would expect the error message to be written into "myerr.txt", instead
> it is displayed on the console, on regular stderr (?) and "myerr.txt" is
> empty. I guess I misunderstood something ...

I'd say you have to handle the exception before the original stderr is
restored, e. g:

import sys
import traceback
myerr = file("myerr.txt", "w")
sys.stderr = myerr
try:
    try:
        raise Exception("some error")
    except:
        traceback.print_exc()
finally:
    myerr.close()
    sys.stderr = sys.__stderr__

As print_exc() allows you to specify a file parameter, you could of course
entirely drop the try ... finally.

Peter




More information about the Python-list mailing list