如何在Mac OS X的python中处理raw_input()的EOFError

时间:2010-02-04 06:53:13

标签: python macos eof eoferror

我的python程序有两次调用raw_input()

第一个raw_input()是从用户那里获取多行输入。用户可以在输入结束时发出Ctrl + D(在Windows中为Ctrl + Z)。

第二个raw_input()应该从用户那里获得另一个带有(y / n)类型提示的输入。

不幸的是(仅限Mac OS X?),当第一个raw_input()提示符终止stdin(使用Ctrl + D)时,第二个EOFError会引发raw_input()

请参阅下面的示例代码以获取更多说明 -

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

节目输出:

-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

如何在第二次提示时不要提出EOFError。请帮忙!

修改

我编辑了我的问题以保持简单。

我在Linux系统中运行了上面的代码,它没有任何问题。也就是说,第二个raw_input()提示用户接收'(y / N)'选项。

1 个答案:

答案 0 :(得分:6)

当标准输入终止时(通过按下控制-D,在Unix派生系统中 - 我认为它是Windows中的控件-Z),这是非常正常的,此后保持终止(除非你当然,关闭并重新打开它。