Behaviour of fileinput with stdin

Brad Bollenbach bbollenbach at shaw.ca
Wed Apr 3 19:25:33 EST 2002


Given the following code:

#!/usr/bin/python
import fileinput
for line in fileinput.input():
    print line

saved as, foo.py...

$ ./foo.py
this is some input
this is more stuff
EOF <-- (as in, on this line the ONLY thing i do is hit Ctrl-D)

Why must I hit Ctrl-D /twice/ for it to "take" to the EOF? And why does
it merely print out what I've just entered, and then keep prompting me,
instead of ending immediately, as Perl's <> operator does?

e.g.
#!/usr/bin/perl
while (<>) { print }

saved as foo.pl

$ ./foo.pl
this is some text
this is some text   <-- immediately prints it back out
EOF <-- (same as above)
$

It was my understanding that fileinput.input() is the Pythonic Way of
doing Perl's <>. Can someone please explain the difference in behaviour
between the two? Specifically:

1.) Why doesn't fileinput.input() immediately print the lines?
2.) Why won't it "take" to the EOF until I hit EOF a second time?

--
Brad



More information about the Python-list mailing list