-1

Say I have a python program composed of three lines.

if __name__=“__main__”:
   foo( )
   print “Hello”

Here, foo( ) is a third-part function that outputs things to the standard output. E.g, foo( ) has only one line print 'I am here'. The point is that I have no permission to change foo() which may contain output statements, and I don't want to mix its output with mine.

Question:

How can I change the third line of the program above (print “Hello”), so that this program

1.only prints “Hello”, and

2.does not print anything from foo( )?

Thanks for your ideas.

zell
  • 9,830
  • 10
  • 62
  • 115

1 Answers1

4

You can redirect stdout to os.devnull (the null device); the following:

import os
import sys
def foo():
  print "foo"
if __name__ == "__main__":
  out = sys.stdout
  null = open(os.devnull, 'w')
  sys.stdout = null
  foo()
  sys.stdout = out
  print "Hello"

will print Hello. You can read about the null device here.

EvenLisle
  • 4,672
  • 3
  • 24
  • 47