Eoferror: Eof When Reading A Line

0
915

Eoferror: Eof When Reading A Line

When one of the built-in functions input() or raw input() encounters an end-of-file condition (EOF) without reading any data, an EOFError is raised. When using online IDEs, you can encounter this error. This happens when the user is asked for feedback but does not have any in the input box. In Python, we can solve this problem by using the try and except keywords.

Example:

When there is no input provided to the online IDE, this code will produce an EOFError.

n = int(input())
print(n * 10)

try:
n = int(input())
print(n * 10)
except EOFError as e:
print(e)

Output:

EOF when reading a line

When a built-in function like input() or raw input() fails to read any data before reaching the end of its input stream, an EOFError is raised. Read() and other file methods return an empty string at the end of the file.

The following code is rewritten to capture the EOFError and specify its type.

Example

eofError.py
try:
while True:
data = raw_input(‘prompt:’)
print ‘READ:’, data
except EOFError as e:
print e
Then if we run the script at the terminal
$ echo hello | python eofError.py

Output

prompt:READ: hello
prompt:EOF when reading a line

LEAVE A REPLY

Please enter your comment!
Please enter your name here