Python 阅读一行时如何删除EOFError:EOF?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42891603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove EOFError: EOF when reading a line?
提问by Jeff
Basically, I have to check whether a particular pattern appear in a line or not. If yes, I have to print that line otherwise not. So here is my code:
基本上,我必须检查特定模式是否出现在一行中。如果是,我必须打印该行,否则不打印。所以这是我的代码:
p = input()
while 1:
line = input()
a=line.find(p)
if a!=-1:
print(line)
if line=='':
break
This code seems to be good and is being accepted as the correct answer. But there's a catch. I'm getting a run time error EOFError: EOF when reading a line which is being overlooked by the code testing website.
这段代码似乎很好,并被接受为正确答案。但有一个问题。我在读取代码测试网站忽略的行时收到运行时错误 EOFError: EOF。
I have three questions: 1) Why it is being overlooked? 2) How to remove it? 3) Is there a better way to solve the problem?
我有三个问题:1)为什么它被忽视了?2)如何去除?3)有没有更好的方法来解决这个问题?
回答by Giannis Spiliopoulos
Nothing is overlooked. As per the documentationinput
raises an EOFError when it hits an end-of-file condition. Essentially, input
lets you know we are done here there is nothing more to read. You should await for this exception and when you get it just return from your function or terminate the program.
没有什么是被忽视的。根据文档input
,当遇到文件结束条件时会引发 EOFError。从本质上讲,input
让您知道我们已经完成了,没有什么可阅读的了。你应该等待这个异常,当你得到它时,只需从你的函数返回或终止程序。
def process_input():
p = input()
while True:
try:
line = input()
except EOFError:
return
a = line.find(p)
if a != -1:
print(line)
if line=='':
return
回答by Suraj Kumar
You can use try-except block in your code using EOFError.
您可以使用 EOFError 在代码中使用 try-except 块。