Redirecting stderr to null and revert

greg greg at cosc.canterbury.ac.nz
Tue Aug 7 11:42:16 CEST 2007


reubendb wrote:
> 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!

--
Greg



More information about the Python-list mailing list