How to stop output and printing

The essential problem is how to not get output from a program.

Let me explain: Ete2, a Python module for representing phylogenies, has a number of dependencies (MySQLdb, Numpy, PyQt, etc.) that it doesn’t necessarily need and it can be installed without them. If you don’t use the associated functionality, you won’t need these dependencies. But, irritatingly, ete2 tries to import them anyway at the root level. If they are not present, it catches the ImportError and and write warning messages to stdout and stderr for each one, So ete2 is imported successfully, but with the clutch of error statements:

>>> import ete2
Clustering module could not be loaded
No module named numpy
MySQLdb module could not be loaded
No module named MySQLdb
Treeview module could not be loaded
No module named PyQt4.QtGui

which is cosmetically irritating and problematic is you’re catching all the output from a process (like in a CGI environment). So output has to be temporarily silenced.

We can silent output by reassigning the stderr and stdout members of the sys module to /dev/null. Of course, you should revert the assignment afterwards or you’ll be killing any future output of your program. Remember to flush the handles to clear any outstanding data. The solution below is written as a Python context manager, although it could be easily written in a more procedural way:

import os, sys

class SuppressAllOutput (object):
   def __enter__(self):
      sys.stderr.flush()
      self.old_stderr = sys.stderr
      sys.stderr = open('/dev/null', 'a+', 0)
      sys.stdout.flush()
      self.old_stdout = sys.stdout
      sys.stdout = open('/dev/null', 'a+', 0)

   def __exit__(self, exc_type, exc_value, traceback):
      sys.stderr.flush()
      sys.stderr = self.old_stderr
      sys.stdout.flush()
      sys.stdout = self.old_stdout

print >>sys.stdout, "printing to stdout before suppression"
print >>sys.stderr, "printing to stderr before suppression"

with SuppressAllOutput():
   import ete2
   print >>sys.stdout, "printing to stdout during suppression"
   print >>sys.stderr, "printing to stderr during suppression"

print >>sys.stdout, "printing to stdout after suppression"
print >>sys.stderr, "printing to stderr after suppression"