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?

3 Answers

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

VS CODE FIX:

I was getting the same error using VS Code and this worked for me. I had modified the “console” line in my launch.json file to be this:

"console": "internalConsole"

I did this hoping to keep the path from printing every time I (F5) ran my program. This modification however causes it to run in the debug console which apparently doesn’t like the input function.

I’ve since changed it back to:

"console": "integratedTerminal"

And at the start of my program I just clear the terminal screen using this code (I’m in windows):

#windows command to clear screen
import os
os.system('cls')

Now when I (F5) run my program in VScode it executes in the built in terminal, clears the path garbage that gets displayed first and works like you would expect with no exceptions. My guess is that the code testing website you are using is running in some kind of debug console similar to what was happening in VSCode because your code works fine on repl.it (https://repl.it/languages/python3). There is nothing wrong with your code and there is nothing normal or expected about this EOF error.

You can use try-except block in your code using EOFError.

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Privacy Policy