18

I want to do something like:

for line in sys.stdin:
    do_something()
    if is **END OF StdIn**:
        do_something_special()

After a few tries, for now I am doing this:

while True:
    try:
        line = sys.stdin.next()
        print line,
    except StopIteration:
        print 'EOF!'
        break

Or with this:

while True:
    line = sys.stdin.readline()
    if not line:
        print 'EOF!'
        break
    print line,

I think both above ways are very similar. I want to know is there a more elegant (pythonic) way to do this?


Early failed tries:

I first tried to catch the StopIteration from inside or outside of a for loop, but I soon realize that since the StopIteration exception is build into for loop itself, both following code snippet didn't work.

try:
    for line in sys.stdin:
        print line,
except StopIteration:
    print 'EOF'

or

for line in sys.stdin:
    try:
        print line,
    except StopIteration:
        print 'EOF'
Community
  • 1
  • 1
YaOzI
  • 16,128
  • 9
  • 76
  • 72
  • Have you found the answer to your question? I am facing the same problem in 2.7. There ought to be a simple solution. – Codism Jun 29 '17 at 16:12

2 Answers2

28
for line in sys.stdin:
    do_whatever()
# End of stream!
do_whatever_else()

It's that simple.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • 1
    I tried this one in python 2.7/windows/debian; the loop body does not start immediately after 'enter' is hit, which is not useful. However, the code works as expected in Python 3. – Codism Jun 29 '17 at 16:16
  • @Codism: That sounds like input buffering, either in the file object implementation or at the OS level. It's normal. If you want different buffering behavior, there are ways to get that, but it's not the subject of this question. – user2357112 Jun 29 '17 at 18:38
  • 1
    This will hang forever if the input dosen't end in a newline. – meawoppl Sep 18 '17 at 01:42
  • 2
    @meawoppl: [Can't reproduce.](https://ideone.com/Gf9FZL) As long as the input stream actually ends (instead of just being left open), the loop should terminate. If you're running this from the terminal, you may have to hit Ctrl-D or something to signal end-of-input. – user2357112 Sep 18 '17 at 02:31
  • @user2357112 please add a comment this is correct only for Python 3 – Roman M Feb 05 '18 at 12:02
16

Use try/except. Input

When EOF is read, EOFError is raised.

while True:
    try:
        s=input("> ")
    except EOFError:
        print("EOF")
        break
KIM Taegyoon
  • 1,917
  • 21
  • 18