weird behavior in 'for line in sys.stdin'

Michael McFarland sidlonDoesntLikeSpam at yahoo.com
Wed Apr 30 01:25:48 CEST 2003


   Here's basic three ways of printing lines from standard input.  If
standard input is coming from a file or other program, all three behave
properly.  When run interactively from a bash prompt, however, there are
three different behaviors.  Method #3's behavior seems especially odd.  Is
there a bug here?

METHOD #1:
while 1:
  line = sys.stdin.readline()
  if not line:
    break
  line = line.rstrip()
  print "LINE: ", line

METHOD #2:
for line in sys.stdin.readlines():
   line = line.rstrip()
   print "LINE: ", line

METHOD #3:
for line in sys.stdin:    [or sys.stdin.xreadlines()]
   line = line.rstrip()
   print "LINE: ", line


---
Here's what happens when I type 'a', 'b', 'c', then 'ctrl-d' interactively
with each:

  METHOD #1:
a
LINE:  a
b
LINE:  b
c
LINE:  c
$>

  METHOD #2:
a
b
c
LINE:  a   <printed after crtl-D>
LINE:  b
LINE:  c
$>

  METHOD #3:
a
b
c
LINE:  a   <printed after crl-D>
LINE:  b
LINE:  c
<doesn't return to shell>
d
e
f
LINE:  d   <printed after a 2nd ctrl-D>
LINE:  e
LINE:  f
< and so on, until ctrl-D is hit twice in succession >
$>


   I can see why method #2 will obviously not print anything until
"readlines()" finishes.  But I would generally have expected method #3 with
its lazy evaluation to work like #1.  Can anyone shed some light on what's
really going on w/ 'for line in sys.stdin'?

  - Michael






More information about the Python-list mailing list