-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.

2
  • 1
    If you want to access the value later you can store it in a StringIO object pastebin.com/NHWAjJQv Commented Apr 27, 2015 at 19:55
  • 1
    @PadraicCunningham It is good to know that. Thanks. Commented Apr 27, 2015 at 19:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks so much for your quick response. I have been looking for something like >/dev/null.
No need to thank me - rather accept my question, I don't mind the reputation ;P

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.