Home > Programming & scripting, Python > Cross-platform suppressing of output in python

Cross-platform suppressing of output in python

January 5th, 2008

A common way to suppress output under Unix/Linux in python is by doing

import sys
sys.stdout = open("/dev/null","w")
print "Hello world!" # Will not be printed to stdout

The reason for this could for an example be to let a forked process run silently, or something similar which could not be achieved by simply redirecting the entire application to /dev/null.

The issue with this is that this won’t work on non-unix systems such as windows, which normally isn’t an issue, but if you want platform independency then it isn’t very hard to achieve. Simply create a “file-like object” which implements write, and let it do nothing. This will work on all systems.

import sys

class Silencer(object):
  def write(self, data):
    pass

sys.stdout = Silencer()
print "Hello world!" # Will not be printed to stdout

If you know that you are using other methods of stdout such as writelines, implement them as well.

buffi Programming & scripting, Python

  1. Rhino
    February 4th, 2008 at 13:27 | #1

    os.devnull…

  2. February 9th, 2008 at 13:44 | #2

    I did not know about os.devnull. Thanks for telling me about it.
    It pretty much makes this blog post useless :)

  1. No trackbacks yet.