Stopping a fucntion from printing its output on screen

Jeremy Sanders jeremy+complangpython at jeremysanders.net
Wed Oct 17 11:01:45 EDT 2007


sophie_newbie wrote:

> Hi, in my program i need to call a couple of functions that do some
> stuff but they always print their output on screen. But I don't want
> them to print anything on the screen. Is there any way I can disable
> it from doing this, like redirect the output to somewhere else? But
> later on in the program i then need to print other stuff so i'd need
> to re-enable printing too. Any ideas?

If they are python functions, this hack should work...

import sys

class NullWriter(object):
    def write(self, arg):
        pass

def testfunc():
    print "this is a test"

nullwrite = NullWriter()
oldstdout = sys.stdout
sys.stdout = nullwrite  # disable output
testfunc()
sys.stdout = oldstdout  # enable output
testfunc()


-- 
Jeremy Sanders
http://www.jeremysanders.net/



More information about the Python-list mailing list