What is print? A function?

Steven Bethard steven.bethard at gmail.com
Sun Jan 23 21:46:04 CET 2005


Frans Englich wrote:
> The reason I thinks about this is I need to implement a debug print for my 
> program; very simple, a function/print statement that conditionally prints 
> its message whether a bool is true. Not overly complex.

Sounds like you want to override sys.stdout:

py> class ConditionalWriter(object):
...     def __init__(self, outfile, cond=True):
...         self.outfile = outfile
...         self.cond = cond
...     def write(self, text):
...         if self.cond:
...             self.outfile.write(text)
...
...
py> import sys
py> writer = ConditionalWriter(sys.stdout)
py> sys.stdout = writer
py> print "hi!"
hi!
py> writer.cond = False
py> print "hi!"
py> writer.cond = True
py> print "hi!"
hi!

You probably want to restore sys.stdout when you're done too:

py> sys.stdout = writer.outfile
py> writer.cond = False
py> print "hi!"
hi!

That said, you probably _really_ want the logging module:
     http://docs.python.org/lib/module-logging.html

Steve



More information about the Python-list mailing list