By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
439,985 Members | 1,574 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 439,985 IT Pros & Developers. It's quick & easy.

Redirecting stderr to null and revert

P: n/a
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
Share this Question
Share on Google+
1 Reply


P: n/a
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.