Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to catch EOFError Exception in Python?

If I run this code at the terminal as follows

#eofError.py
while True:
       data = raw_input('prompt:')
       print 'READ:', data
$ echo hello | python eofError.py

I get an error

How do I catch this exception and know its type?


1 Answer
codefoxx

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.

#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
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.