简体   繁体   English

从标准输入读取EOF错误-Python3

[英]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: 运行此脚本并按CTR-D结束对程序的输入时,出现以下错误:

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; 使用input ,无需发送EOF即可结束输入。 just press enter. 只需按Enter。 input is designed to read until a newline character is sent. input被设计为读取直到发送换行符。

If you're looking for a way to break out of the while loop, you could use CTRL+D, and just catch the EOFError : 如果您正在寻找一种打破while循环的方法,则可以使用CTRL + D并捕获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. 这不太可能帮助阿波罗(此外,问题已经4岁了),但这可能会帮助像我这样的人。

I had this same issue and without hitting a single key , the same code would terminate immediately into EOFError. 我遇到了同样的问题,并且没有按任何键 ,相同的代码将立即终止为EOFError。 In my case, culprit was another script executed earlier in the same terminal, which had set stdin into non-blocking mode. 就我而言,罪魁祸首是先前在同一终端中执行的另一个脚本,该脚本已将stdin设置为非阻塞模式。

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. 我确定了令人讨厌的Python脚本并进行了更正。 Other scripts with input() now work just fine after it. 现在,其他带有input()的脚本也可以正常工作。

Edit (plus couple of typos above): This should let you see if STDIN is non-blocking mode: 编辑(上面有几个错字):这应该让您查看STDIN是否为非阻止模式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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