Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Handle EOFError for raw_input() in python in Mac OS X

My python program has two calls to raw_input()

The first raw_input() is to take multiline input from the user. The user can issue Ctrl+D (Ctrl+Z in windows) for the end of input.

Second raw_input() should take another input from user with (y/n) type prompt.

Unfortunately (in Mac OS X only?), second raw_input() raises EOFError when the stdin is terminated (with Ctrl+D) at first raw_input() prompt.

Please see my example code below for more explanation -

mailBody = ''
signature = 'Later!'
print 'Compose your mail:'
while True:
    try:
        # Hit ^D after entering some text
        mailBody+= raw_input()
        mailBody+='\n'
    except EOFError:
        break

# This raw_input() throws EOFError too. Because, stdin is terminated for the session
# when EOF (^D) is issues at first raw_input() method (Where as, it doesn't raise EOFError in Linux)
opt = raw_input("Do you want to add signature to your mail? (y/N): ").lower()
print '-'*10+'Your Mail'
if opt == 'y':
    print mailBody+"\n"+signature
else:
    print mailBody
print '-'*19

The program output:

-1- abhinay@MacBook code/py % python prompt.py                                                        
Compose your mail:
hello there!
how is everybody?
Do you want to add signature to your mail? (y/N): Traceback (most recent call last):
  File "prompt.py", line 11, in <module>
    opt = raw_input("Do you want to add signature to your mail? (y/N): ").lower()
EOFError

How can I make second prompt not to raise EOFError. Please help!

EDIT:

I've edited my question to keep it simple.

I ran my above code in Linux System, it works without any issue. That is, the user was prompted at second raw_input() to receive '(y/N)' choice.

like image 885
abhiomkar Avatar asked Feb 04 '10 06:02

abhiomkar


People also ask

How do I bypass EOF error in Python?

The best practice to avoid EOF in python while coding on any platform is to catch the exception, and we don't need to perform any action so, we just pass the exception using the keyword “pass” in the “except” block.

What does EOFError EOF when reading a line mean?

You should get an error like EOFError: EOF when reading a line. The acronym EOF stands for End Of File. This message literally means that the program called input() but failed to have any available input to read.


1 Answers

It's quite normal that when standard input is terminated (by hitting control-D, in Unix-derived systems -- I think it's control-Z in Windows), it stays terminated thereafter (unless you close and re-open it in the meantime, of course).

like image 180
Alex Martelli Avatar answered Oct 03 '22 02:10

Alex Martelli