Redirecting stderr to null and revert

reubendb reubendb at gmail.com
Mon Aug 6 18:26:53 EDT 2007


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




More information about the Python-list mailing list