Something that Perl can do that Python can't?
Andrew Dalke
dalke at dalkescientific.com
Fri Jul 22 19:49:41 EDT 2005
Dr. Who wrote:
> Well, I finally managed to solve it myself by looking at some code.
> The solution in Python is a little non-intuitive but this is how to get
> it:
>
> while 1:
> line = stdout.readline()
> if not line:
> break
> print 'LINE:', line,
>
> If anyone can do it the more Pythonic way with some sort of iteration
> over stdout, please let me know.
Python supports two different but related iterators over
lines of a file. What you show here is the oldest way.
It reads up to the newline (or eof) and returns the line.
The newer way is
for line in stdout:
...
which is equivalent to
_iter = iter(stdout)
while 1:
try:
line = _iter.next()
except StopIteration:
break
...
The file.__iter__() is implemented by doing
a block read and internally breaking the block
into lines. This make the read a lot faster
because it does a single system call for the
block instead of a system call for every
character read. The downside is that the read
can block (err, a different use of "block")
waiting for enough data.
If you want to use the for idiom and have
the guaranteed "no more than a line at a time"
semantics, try this
for line in iter(stdout.readline, ""):
print "LINE:", line
sys.stdout.flush()
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list