reading from sys.stdin

Matimus mccredie at gmail.com
Thu Apr 12 10:25:08 EDT 2007


On Apr 12, 1:20 am, "7stud" <bbxx789_0... at yahoo.com> wrote:
> I can't break out of the for loop in this example:
>
> ------
> import sys
>
> lst = []
> for line in sys.stdin:
>     lst.append(line)
>     break
>
> print lst
> -----------
>
> But, I can break out of the for loop when I do this:
>
> ---------
> import sys
>
> lst = []
> for line in open("aaa.txt"):
>     lst.append(line)
>     break
>
> print lst
> ----------
>
> Why doesn't break work in the first example?

1. Why are you breaking in the for loop? That will only give you the
first line.

2. Your issue is caused by buffered IO. Because of the buffered IO,
your code is equivalent to doing this:

lst = []
s = sys.stdin.read() #All* of the reading up to EOF is done upfront.

for line in s:
    lst.append(line)
    break # I'm sure you don't really want the break here though :)

One way to get around the buffering is to do this:

[code]
# Open a file or the input stream
if filename:
    f = open(filename,"r")
else:
    f = sys.stdin

# Then you check to see if your file is interactive
if f.isatty():
    # This is unbuffered, and will iterate the same as f
    f = iter(raw_input(),"")

# Now do your stuff
lst = []
for line in f:
    lst.append(line)

print lst
[/code]

* well, not ALL, it will read in chunks. But, I think they are 4096
Byte chunks by default.




More information about the Python-list mailing list