菜鸟学Python(2):学而不思则罔
---温铭 http://blog.csdn.net/wayne92
(转贴请注明出处)
---温铭 http://blog.csdn.net/wayne92
(转贴请注明出处)
在Python Tutorial Python3.7.1节里面有一个这样的程序:
def ask_ok(prompt):
while 1:
ok = raw_input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
elif ok in ('n', 'no', 'nop', 'nope'):
return False
else:
print 'yes or no,please'
while 1:
flag = ask_ok('are you really want to quit?')
if flag == True:
break
print 'out'
while 1:
ok = raw_input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
elif ok in ('n', 'no', 'nop', 'nope'):
return False
else:
print 'yes or no,please'
while 1:
flag = ask_ok('are you really want to quit?')
if flag == True:
break
print 'out'
在IDLE下编译运行没有问题,但在 Eclipse3.2.0+Pydev1.2.2下运行就会有问题:不管输入什么,都不会从ask_ok函数中退出。很是怪异。
设置断点调试以后才发现:我输入一个字符串后按回车,ok的值就变成了 输入的字符串+'/r' ,多在后面加了一个'/r'。如果在上面程序中每个和ok比较的字符串后面都加'/r',则程序可以在 Eclipse3.2.0+Pydev1.2.2下面按我原来想的那样运行,但就不能在IDLE下运行了:(
把问题发到邮件列表里面请教,有人建议:在 ok= raw_input(prompt)之后加一个 ok = ok.strip(),去掉最后的回车符。果然,这样在两个地方都可以正常运行了。
”学而不思则罔“,为什么会出现这种情况类?在Python Shell 里面help一下:
help(raw_input)
Help on built-in function raw_input in module __builtin__:
raw_input(...)
raw_input([prompt]) -> string
Read a string from standard input. The trailing newline is stripped.
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
On Unix, GNU readline is used if enabled. The prompt string, if given,
is printed without a trailing newline before reading.
所以,我觉得是Pydev对Python的支持不好,在处理 raw_input函数 的时候没有把最后输入的回车符去掉,以至于引起错误。
PS:啥时候有时间去看看Python的源代码,是用c写的,呵呵,应该看的懂吧:)
补记(2006年7月30日):将这个bug提交给了Pydev的用户组, Fabio Zadrozny 的回复是:
Nope, this is a python bug mixed with a bad specification on how a shell is supposed to behave.
Usually shells put a '/n' when you press enter, but the Eclipse console puts '/r/n' and python does not handle it well, as this is not specified anywhere, and does not seem such awkward, my feeling is that it's a python bug, but you can surely argue the other way... so, you can submit a bug to eclipse.org and python.org and see who'll fix it... (or you can handle it in your program).
Cheers,
Fabio