reading from sys.stdin

7stud bbxx789_05ss at yahoo.com
Fri Apr 13 11:01:11 CEST 2007


Hi,

Thanks for the responses.  My book, Beginning Python: From Novice to
Professional(p. 266) says that "sys.stdin is iterable, just like other
files", so I thought I would test it out.   However, I don't see how
it is acting similar to a file in my example.

I assume all input is buffered by default, so I'm not sure how it
explains things to say that input from sys.stdin is buffered.

> I typed many lines, but lst contains only one item, as expected. Same as
> your regular file example: the file contains many lines, but only the
> first goes into the list.

Interesting example--not as I expected!  But there is a difference in
the two examples isn't there?  When you iterate over a file, the whole
file isn't put into an internal buffer first, is it?


> I don't know if this a python or OS thing, but I know that iterating over a
> file is not like applying successive call to readline method. You should try
> to use readline instead.

I've wondered what the differences were.  Thanks for bringing that
up.  I searched around on google, and PEP 234 has this to say about
that:
------------------------------------
- Files implement a tp_iter slot that is equivalent to
      iter(f.readline, "").  This means that we can write

          for line in file:
              ...

      as a shorthand for

          for line in iter(file.readline, ""):
              ...

      which is equivalent to, but faster than

          while 1:
              line = file.readline()
              if not line:
                  break
              ...
...
Because the file iterator uses an internal buffer, mixing this
    with other file operations (e.g. file.readline()) doesn't work
    right.  Also, the following code:

      for line in file:
          if line == "\n":
              break
      for line in file:
          print line,

    doesn't work as you might expect, because the iterator created by
    the second for-loop doesn't take the buffer read-ahead by the
    first for-loop into account.  A correct way to write this is:

      it = iter(file)
      for line in it:
          if line == "\n":
              break
      for line in
it:
          print line,
--------------------------------------------


> You may want to look at a related issue:
> http://www.python.org/sf/1633941

Bad link.

>This should be f = iter(raw_input,"") and this will end in a EOFError
>and stop on blank line. So you need a wrapper

Why a wrapper?  This example seems to work without error:

lst = []

f = iter(raw_input, "")
for line in f:
    lst.append(line)

print lst






More information about the Python-list mailing list