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

Published on 06-Dec-2017 13:09:42