non OO behaviour of file

Michael Hoffman cam.ac.uk at mh391.invalid
Wed Jun 15 10:49:27 EDT 2005


Robin Becker wrote:
> I recently tried to create a line flushing version of sys.stdout using
> 
> class LineFlusherFile(file):
>     def write(self,s):
>         file.write(self,s)
>         if '\n' in s:
>             self.flush()
> 
> but it seems that an 'optimization' prevents the overriden write method 
> from being used. I had thought python was more regular than it appears 
> to be.
> 
> Is there a better way to accomplish the intention of the above than
> 
> class LineFlusherFile:
>     def __init__(self,*args):
>         self._f = open(*args)
>     def __getattr__(self,a):
>         return getattr(self._f,a)
>     def write(self,s):
>         self._f.write(s)
>         if '\n' in s:
>             self._f.flush()

Well, you could use python -u:

"""-u     Force  stdin,  stdout  and stderr to be totally unbuffered. 
On systems where it matters, also put stdin, stdout and stderr in binary 
  mode. Note that there is internal buffering in xreadlines(), 
readlines() and file-object iterators  ("for  line  in sys.stdin") which 
  is not influenced by this option.  To work around this, you will want 
to use "sys.stdin.readline()" inside a "while 1:" loop."""

Within pure Python there's not a better way that I know of. I keep a 
slightly-more generalized Surrogate class around to deal with this 
pattern, and then my LineFlusherFile would be a subclass of that. But 
it's the same thing, really.
-- 
Michael Hoffman



More information about the Python-list mailing list