本文介绍了如何在Mac OS X中的python中处理raw_input()的EOFError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的python程序有两个对raw_input()

My python program has two calls to raw_input()

第一个raw_input()是接受用户的多行输入.用户可以在输入结束时发出Ctrl + D(在Windows中为Ctrl + Z).

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.

第二个raw_input()应该使用(y/n)类型的提示从用户那里再次输入.

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

不幸的是(仅在Mac OS X中?),当stdin在第一个raw_input()提示符处终止(用Ctrl + D组合键)时,第二个raw_input()会升高EOFError.

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

程序输出:

-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.请帮忙!

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

为了让问题更简单,我已经编辑了问题.

I've edited my question to keep it simple.

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

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.

推荐答案

当标准输入终止时(在Unix衍生的系统中,通过按Control-D来敲击-我认为在Windows中是Control-Z)是很正常的,此操作保持在此之后终止(当然,除非您同时关闭并重新打开它).

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

这篇关于如何在Mac OS X中的python中处理raw_input()的EOFError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:49
查看更多