non OO behaviour of file

R

Robin Becker

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()

I wondered if I could make a file subclass somehow fail the PyFile_Check which
allows the optimization.
 
M

Michael Hoffman

Robin said:
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.
 
R

Robin Becker

Michael Hoffman wrote:
......
Well, you could use python -u:

unfortunately this is in a detached process and I am just reopening stdout
as an ordinary file so another process can do tail -F on it. I imagine ther
ought to be an os dependant way to set the file as unbuffered, but can't
remember/find out what it ought to be.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,241
Messages
2,571,223
Members
47,858
Latest member
SangC9100

Latest Threads

Top