开发者

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 promp开发者_运维问答t 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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜