我想做这样的事情:
for line in sys.stdin:
do_something()
if is **END OF StdIn**:
do_something_special()
经过几次尝试,现在我正在这样做:
while True:
try:
line = sys.stdin.next()
print line,
except StopIteration:
print 'EOF!'
break
或者用这个:
while True:
line = sys.stdin.readline()
if not line:
print 'EOF!'
break
print line,
我认为以上两种方式非常相似。我想知道是否有更优雅的(Pythonic)方法来做到这一点?
我首先尝试从
StopIteration
循环内部或外部捕获 for
,但我很快意识到,由于 StopIteration
异常是 build 到 for
循环本身,因此以下代码片段都没有工作。
try:
for line in sys.stdin:
print line,
except StopIteration:
print 'EOF'
或
for line in sys.stdin:
try:
print line,
except StopIteration:
print 'EOF'
for line in sys.stdin:
do_whatever()
# End of stream!
do_whatever_else()
就这么简单。
使用尝试/例外。 输入
读取 EOF 时,会引发 EOFError。
while True:
try:
s=input("> ")
except EOFError:
print("EOF")
break
使用迭代器
from typing import Iterable
def last_line(itr: Iterable[str]) -> (bool, str):
last = None
for line in itr:
if last is not None:
yield False, last
last = line
if last is not None:
yield True, last
像这样
for last, line in last_line(sys.stdin):
if not last:
do_something()
else:
do_something_special()