Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

python - How to remove EOFError: EOF when reading a line?

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Nothing is overlooked. As per the documentation input 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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...