How to catch EOFError Exception in Python?

PythonServer Side ProgrammingProgramming

An EOFError is raised when a built-in function like input() or raw_input() do not read any data before encountering the end of their input stream. The file methods like read() return an empty string at the end of the file.

The given code is rewritten as follows to catch the EOFError and find its type.

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


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

Updated on 12-Feb-2020 10:50:04