我想做的事情如下:
for line in sys.stdin:
do_something()
if is **END OF StdIn**:
do_something_special()
Run Code Online (Sandbox Code Playgroud)
经过几次尝试,现在我这样做:
while True:
try:
line = sys.stdin.next()
print line,
except StopIteration:
print 'EOF!'
break
Run Code Online (Sandbox Code Playgroud)
或者用这个:
while True:
line = sys.stdin.readline()
if not line:
print 'EOF!'
break
print line,
Run Code Online (Sandbox Code Playgroud)
我认为以上两种方式非常相似.我想知道有更优雅(pythonic)的方式吗?
我首先尝试StopIteration从for循环内部或外部捕获,但我很快意识到,由于StopIteration异常是构建到 for循环本身,所以下面的代码片段都不起作用.
try:
for line in sys.stdin:
print line,
except StopIteration:
print 'EOF'
Run Code Online (Sandbox Code Playgroud)
要么
for line in sys.stdin:
try:
print line,
except StopIteration:
print 'EOF'
Run Code Online (Sandbox Code Playgroud)
use*_*ica 16
for line in sys.stdin:
do_whatever()
# End of stream!
do_whatever_else()
Run Code Online (Sandbox Code Playgroud)
就这么简单.
使用try/except.输入
读取EOF时,会引发EOFError.
while True:
try:
s=input("> ")
except EOFError:
print("EOF")
break
Run Code Online (Sandbox Code Playgroud)