1

I'm receiving the following error when I run this script and press CTR-D to end my input to the program:

The Error:

My-MacBook-Pro-2:python me$ python3 test.py 
>> Traceback (most recent call last):
  File "test.py", line 4, in <module>
    line = input(">> ")
EOFError

The Script

import sys

while(1):
    line = input("Say Something: ")
    print(line)

Why is this happening?

3
  • Has anything else changed in test.py vs what you copied and pasted? Because the Traceback as well as the output shows a completely different input command. I cannot replicate this error on my system. (I get KeyboardInterrupt as expected.) Commented Oct 10, 2014 at 21:19
  • 1
    Are you sure you're not sending a CTRL+D? That sends an EOF character to stdin, which would explain what you're seeing. Commented Oct 10, 2014 at 21:21
  • @dano I apologize, I mean to type CTRL+D. Yes, essentially my question is how do I handle EOF when reading stdin? Commented Oct 10, 2014 at 21:28

2 Answers 2

6

This is not likely to help Apollo (besides, question is 4 years old), but this might help someone like myself.

I had this same issue and without hitting a single key, the same code would terminate immediately into EOFError. In my case, culprit was another script executed earlier in the same terminal, which had set stdin into non-blocking mode.

Should the cause be the same, this should help:

flag = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL)
fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, flag & ~os.O_NONBLOCK)

I identified the offending Python script and made the correction. Other scripts with input() now work just fine after it.

Edit (plus couple of typos above): This should let you see if STDIN is non-blocking mode:

import os
import sys
import fcntl
flag = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL)
print(
    "STDIN is in {} mode"
    .format(
        ("blocking", "non-blocking")[
            int(flag & os.O_NONBLOCK == os.O_NONBLOCK)
        ]
    )
)
Sign up to request clarification or add additional context in comments.

Comments

1

When you use input, there's no need to send EOF to end your input; just press enter. input is designed to read until a newline character is sent.

If you're looking for a way to break out of the while loop, you could use CTRL+D, and just catch the EOFError:

try:
    while(1):
        line = input("Say Something: ")
        print(line)
except EOFError:
    pass

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.