Stopping a fucntion from printing its output on screen

Paul Hankin paul.hankin at gmail.com
Thu Oct 18 04:00:56 EDT 2007


On Oct 17, 3:57 pm, sophie_newbie <paulgeele... at gmail.com> 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?

Yes, in your functions that you may or may not want to print stuff,
declare them with a stream parameter that defaults to stdout.

For example:

import sys

def f(i, out = sys.stdout)
   # Do something...
   print >>out, "i is %d" % i

Then usually, you call
f(10)

But when you want to elide the output, use Jeremy's nullwriter:
class NullWriter(object):
    def write(self, arg):
        pass
nullwriter = NullWriter()

f(10, out = nullwriter)

Having the output stream explicit like this is much better style than
abusing sys.stdout, and it won't go wrong when errors occur. It's the
same idea as avoiding global variables.

--
Paul Hankin




More information about the Python-list mailing list