472,119 Members | 1,552 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,119 software developers and data experts.

Redirecting stderr to null and revert

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

Aug 6 '07 #1
1 2800
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
Aug 7 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by David Douard | last post: by
3 posts views Thread by Laszlo Zsolt Nagy | last post: by
9 posts views Thread by Fuzzyman | last post: by
18 posts views Thread by praetor.michael | last post: by
116 posts views Thread by dmoran21 | last post: by
10 posts views Thread by Guillaume Dargaud | last post: by
1 post views Thread by Lincoln Yeoh | last post: by
1 post views Thread by n00b | last post: by
reply views Thread by leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.