redirecting stderr

M

Michele Simionato

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 ...

Michele Simionato
 
R

Roland Heiber

Michele said:
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 ...

Michele Simionato

Hi,

os.close(2)
os.dup2(myerr.fileno(), 2)

Works, but is dirty ...

HtH, Roland
 
P

Peter Otten

Michele said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top