如何在Mac OS X中的python中处理raw_input()的EOFError
问题内容:
我的python程序有两个调用 raw_input()
首先raw_input()
是接受用户的多行输入。用户可以在输入结束时发出Ctrl + D(在Windows中为Ctrl + Z)。
其次,raw_input()
应使用(y / n)类型提示符从用户那里再次输入。
不幸的是(仅在Mac OS X中?),当标准输入在第一个提示符处终止(用Ctrl +
D组合键)时,秒数raw_input()
会增加。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)”选择。
问题答案:
正常情况是,当标准输入终止时(在Unix衍生系统中,通过按Control-D来敲击-我认为它在Windows中是control-Z),此后它将 保持
终止状态(除非您同时关闭并重新打开它,当然)。