在玩sys.stdin.read()
(终端,Mac OS Sierra)时,发现它变得无法使用的奇怪行为。发生了什么事?
# Python 2.7.13
import sys
sys.stdin.read()
# waits for input
# user presses ctrl-d (without any input)
# returns ''
sys.stdin.read()
# doesn't wait for input
# immediately returns ''
sys.stdin.read()
# ''
sys.stdin.read()
# ''
注意: ctrl + d = Mac上的EOF,Windows上的 ctrl + z
更新:我注意到任何长度为5的字符串都有相同的行为,只有一个新行...更短/更长的字符串或更多/更少的新行表现正常......
# Python 2.7.13
import sys
sys.stdin.read()
12345
# press ctrl-d twice (only way to make single line string work?)
'12345'
# worked properly
sys.stdin.read()
1234
# user presses return and then ctrl-d
'1234\n'
# worked properly
sys.stdin.read()
12345
# return, return, ctrl-d
'12345\n\n'
# worked properly
sys.stdin.read()
12345
# return, ctrl-d
'12345\n'
# didn't work...see next call
sys.stdin.read()
# doesn't wait for input
# immediately returns ''
''
我想了解导致这种行为的原因,因为我在程序中使用它。我一定会在代码中检查它,但仍想了解如何避免这两个不起作用的实例。