[Tutor] class Writer

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu May 25 03:02:19 CEST 2006



On Wed, 24 May 2006, Christopher Spears wrote:

> I've been working my way through an online tutorial and came across the 
> following sample script:
>
> import sys
>
> class Writer:
>    def __init__(self, filename):
>        self.filename = filename
>    def write(self, msg):
>        f = file(self.filename, 'a')
>        f.write(msg)
>        f.close()

Just as a side note: the 'logging' module in the Standard Library would 
probably be the way to handle things like this.

     http://www.python.org/doc/lib/module-logging.html


> I understand that the class is taking the strings from stdout (supplied 
> by the print statements) and writing them to a text file.

Not exactly.  Something more subtle is happening.  Every call to the print 
statement causes Python to do something like:

     print foo    ====>   sys.stdout.write(str(foo) + "\n")

At least, to a first approximation, that's what 'print' does.

We can try it out by, from a clean interpreter, doing:

######
import sys
sys.stdout.write("hello")
sys.stdout.write("world")
######

We should see "helloworld" because we have not told sys.stdout to write a 
newline to separate the two words.


Going back to the code that you show:

     sys.stdout = Writer('tmp.log')

is explicitely reassigning the standard output file to something else 
entirely.  Future print statements talk to the Writer instance as if it 
were standard output.


Does this distinction clear things up?


More information about the Tutor mailing list