简体   繁体   中英

EOF error when reading from stdin - Python3

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?

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

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)
        ]
    )
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM