EOFError: EOF when reading a line
So as we can see in the pictures above, despite having produced the expected output, our test case fails due to a runtime error EOFError i.e., End of File Error. Let’s understand what is EOF and how to tackle it.
What is EOFError
In Python, an EOFError is an exception that gets raised when functions such as input() or raw_input() in case of python2 return end-of-file (EOF) without reading any input.
When can we expect EOFError
We can expect EOF in few cases which have to deal with input() / raw_input() such as:

Interrupt code in execution using ctrl+d when an input statement is being executed as shown below
Another possible case to encounter EOF is, when we want to take some number of inputs from user i.e., we do not know the exact number of inputs; hence we run an infinite loop for accepting inputs as below, and get a Traceback Error at the very last iteration of our infinite loop because user does not give any input at that iteration
Exit fullscreen mode
The code above gives EOFError because the input statement inside while loop raises an exception at last iteration
Do not worry if you don’t understand the code or don’t get context of the code, its just a solution of one of the problem statements on HackerRank 30 days of code challenge which you might want to check
The important part here is, that I used an infinite while loop to accept input which gave me a runtime error.
How to tackle EOFError
We can catch EOFError as any other error, by using try-except blocks as shown below :
Exit fullscreen mode
You might want to do something else instead of just printing «EOF» on the console such as:
Exit fullscreen mode
In the code above, python exits out of the loop if it encounters EOFError and we pass our test case, the problem due to which this discussion began.
alt=»image» width=»880″ height=»433″ />
Hope this is helpful
If you know any other cases where we can expect EOFError, you might consider commenting them below.
Dec 27, 2017 9:30:42 PM | Python Exception Handling — EOFError
A close look at the EOFError in Python, including a functional code sample showing how to handle user input in both Python 2 and Python 3.
Share
Moving along through our in-depth Python Exception Handling series, today we’ll be going over the EOFError. The EOFError is raised by Python in a handful of specific scenarios: When the input() function is interrupted in both Python 2.7 and Python 3.6+, or when input() reaches the end of a file unexpectedly in Python 2.7.
Throughout this article we’ll examine the EOFError by seeing where it resides in the overall Python Exception Class Hierarchy. We’ll also look at some fully functional code examples that illustrate how the different major versions of Python handle user input, and how improper use of this functionality can sometimes produce EOFErrors , so let’s get to it!
The Technical Rundown
All Python exceptions inherit from the BaseException class, or extend from an inherited class therein. The full exception hierarchy of this error is:
- EOFError
- Вопрос задан более двух лет назад
- 21053 просмотра
- Вконтакте
- Вконтакте
Full Code Sample
Below is the full code sample we’ll be using in this article. It can be copied and pasted if you’d like to play with the code yourself and see how everything works.
When Should You Use It?
Before we can take a look at some code samples we need to briefly review the built-in input() function in Python. Simply put, in Python 3 input() presents a console prompt to the user and awaits user input, which is then converted to a string and returned as the result of the input() function invocation. However, Python 2 had a slightly different behavior for input() , as it still prompts the user, but the input the user provides is parsed as Python code and is evaluated as such. To process user input using the Python 3 behavior, Python 2 also included the raw_input() function, which behaves the same as the Python 3 input() function.
To better illustrate these differences let’s take a look at a few simple code snippets, starting with the input_test_3.6.py file:
As you can see, the only thing we’re doing here is requesting user input() two times for a book author and title, then outputting the result to the log. Executing this code in Python 3.6 produces the following output:
That works as expected. After entering The Stand at the prompt for a title and Stephen King at the author prompt, our values are converted to strings and concatenated in the final output. However, let’s try executing the same test in Python 2.7 with the input_test_2.7.py file:
Running this and entering The Stand for a title immediately raises a SyntaxError, with an underlying EOFError :
As discussed earlier, the problem here is how Python 2 interprets input from the, well, input() function. Rather than converting the input value to a string, it evaluates the input as actual Python code. Consequently, The Stand isn’t valid code, so the end of file is detected and an error is thrown.
The resolution is to use the raw_input() function for Python 2 builds, as seen in raw_input_test_2.7.py :
Executing this in Python 2.7 produces the following output:
Everything works just fine and behaves exactly like the input() test running on Python 3.6. However, we also need to be careful that the input isn’t terminated prematurely, otherwise an EOFError will also be raised. To illustrate, let’s execute raw_input_test_2.7.py in Python 2.7 again, but this time we’ll manually terminate the process ( Ctrl+D ) once the title prompt is shown:
Unexpectedly terminating the input raises an EOFError , since the behavior from the Python interpreter’s perspective is identical to if it evaluated input and reached the end of the file. Similarly, let’s perform the same manual termination with input_test_3.6.py running on Python 3.6:
It’s worth noting that the gw_utility helper module isn’t written for Python 2 versions, so we don’t see the fancier error output in the previous Python 2 example, but otherwise the behavior and result is identical in both Python 2 and Python 3.
Airbrake’s robust error monitoring software provides real-time error monitoring and automatic exception reporting for all your development projects. Airbrake’s state of the art web dashboard ensures you receive round-the-clock status updates on your application’s health and error rates. No matter what you’re working on, Airbrake easily integrates with all the most popular languages and frameworks. Plus, Airbrake makes it easy to customize exception parameters, while giving you complete control of the active error filter system, so you only gather the errors that matter most.
Check out Airbrake’s error monitoring software today with a 14-day trial, and see for yourself why so many of the world’s best engineering teams use Airbrake to revolutionize their exception handling practices!
EOFError: EOF when reading a line
I am trying to define a function to make the perimeter of a rectangle. Here is the code:
I think I haven’t left any arguments opened or anything like that.
3 Answers 3
Running it like this produces:
I suspect IDLE is simply passing a single string to your script. The first input() is slurping the entire string. Notice what happens if you put some print statements in after the calls to input() :
Running echo «1 2» | test.py produces
Notice the first print statement prints the entire string ‘1 2’ . The second call to input() raises the EOFError (end-of-file error).
So a simple pipe such as the one I used only allows you to pass one string. Thus you can only call input() once. You must then process this string, split it on whitespace, and convert the string fragments to ints yourself. That is what
Python. Как исправить ошибку EOFError: EOF when reading a line?
Только только притронулся к изучению Python, и уже застрял с ошибкой. Помогите)

Простой 5 комментариев


В вашем случае, вы вероятно используете Python 2, потому что на Python 3 данный код выполняется корректно.
Так же проблема может заключаться в том, что некоторые терминалы неправильно обрабатывают ввод
(Хотя я сам с таким не сталкивался, но читал что и такое бывает в нашем мире)
При использовании input по достижении конца файла или если нажимаете Ctrl+Z и потом Enter, будет сгенерировано исключение EOFError. Чтобы избежать аварийного завершения программы нужно обработать исключение:
try:
a=input(«Enter Your data:»)
print(a)
except EOFError:
print(«Exception handled»)
То есть, когда внутри блока возникнет исключение EOFError, управление будет передано в блок except и после исполнения инструкций в этом блоке программа продолжит нормальную работу.