I'm reading line-by-line from a named pipe which provides lines in a second-by-second rhythm. I was trying the plain simple
for line in file:
processLine(line)
but the processLine()
is never called. (EDIT: It gets called eventually after a lot of lines have been read which takes several minutes.) Investigating with strace
showed that the process is indeed performing an finishing a read()
system call each second and also as expected receives a complete line each time.
I can just guess that the for line in
idiom buffers the input and will call the processLine()
later with each input line, probably when the buffer is full or in case the input terminates (which in my case it never will).
Can I explicitly set the buffer used here to something smaller?
Or is there another way to tweak the thing so that each line is also processed in a second-by-second rhythm?
EDIT:
Currently I am using this workaround:
for line in lineByLine(namedPipe):
…
And this is lineByLine()
:
def lineByLine(openFile):
line = ''
while True:
char = os.read(openFile.fileno(), 1)
if not char:
if line:
yield line
break
line += char
if line.endswith('\n'):
yield line
line = ''
But this ugly workaround is of course no solution.