Redirecting stderr to null and revert

R

reubendb

Hello,
I have some function that output too much stuff to stderr when called,
and I have no control over the function itself. So I thought as a
workaround, I redirect stderr to /dev/null before calling that
function, and then revert the stderr back after calling that
function.
I have something like this:

def nullStderr():
sys.stderr.flush()
err = open('/dev/null', 'a+', 0)
os.dup2(err.fileno(), sys.stderr.fileno())

def revertStderr():
sys.stderr = sys.__stderr__

Then when calling the function, I want to do:
nullStderr()
noisyFunction(foo, bar)
revertStderr()

The problem is the "revertStderr()" doesn't work, ie. I still get no
stderr back after calling it (stderr still redirects to /dev/null). I
want stderr back so that when the script fails in different places
later I can get error messages. What am I missing here ? Thanks a lot
for any help.

RDB
 
G

greg

reubendb said:
def nullStderr():
sys.stderr.flush()
err = open('/dev/null', 'a+', 0)
os.dup2(err.fileno(), sys.stderr.fileno())

def revertStderr():
sys.stderr = sys.__stderr__

You're doing the redirection at one level and
trying to revert it at a different level.

If this is a Python function that's doing its
output by writing to sys.stderr, there's a
much simpler way to do the redirection:

sys.stderr = open('/dev/null', 'w')

(that's the Python builtin function 'open',
not the one in os). Then your revertStderr
function will work.

BTW I'd arrange for the reversion to be done
in a try-finally, e.g.

nullStderr()
try:
do_something()
finally:
revertStderr()

so you won't get stuck with a redirected stderr
if an exception occurs, and thereby not be able
to see the traceback!
 

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

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,817
Latest member
DicWeils

Latest Threads

Top