May 11, 2009

Python - Redirect or Turn Off STDOUT and STDERR

Here is an easy way to temporarily turn off STDOUT or STDERR in your Python program.

First you create a class to replace STDOUT. This is just minimal class with a 'write()' method.

class NullDevice():
    def write(self, s):
        pass

Notice its 'write()' method does nothing. Therefore, when you write to the NullDevice, output goes nowhere and is dropped. All you need to do is assign sys.stdout to this class.

Here is an example of turning STDOUT off and back on:

#!/usr/bin/env python

import sys


class NullDevice():
    def write(self, s):
        pass


print "1 - this will print to STDOUT"

original_stdout = sys.stdout  # keep a reference to STDOUT

sys.stdout = NullDevice()  # redirect the real STDOUT

print "2 - this won't print"

sys.stdout = original_stdout  # turn STDOUT back on

print "3 - this will print to SDTDOUT"

You can also do the same thing with sys.stderr to turn off STDERR.

9 comments:

Anonymous said...

Or just sys.stdout = open('/dev/null') if you're using a unix based system..

Corey Goldberg said...

right.. but like you said, that's not a portable solution.

eMBe said...

sys.stdout = open(os.devnull, 'w') should be pretty portable.

Corey Goldberg said...

thanks eMBe!

Roms said...

You can also not backup the original sys.stdout and restore it using sys.stdout == sys.__stdout__

ambreen tariq said...

in short thanks for the information.

Kalmi said...

hmm... Portable solution:
sys.stderr = None

Major Tal said...

No @Kalmi, None does not allow other statements to .write() to it, causing an exception to be raised.

Denis said...

No, @Roms: some previous code, e.g. unit-test tool, may use some not-default stderr, so backup with restoring in any case is good idea:

import sys, os
old_stderr = sys.stderr
sys.stderr = open(os.devnull, 'w')

try:
some_code_that_writes_to_stderr()

finally:
sys.stderr.close()
sys.stderr = old_stderr