本文介绍了在python中,如何检查标准输入流(sys.stdin)的结尾并对此做一些特殊的操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想执行以下操作:
for line in sys.stdin:
do_something()
if is **END OF StdIn**:
do_something_special()
经过几次尝试,现在我正在做这:
After a few tries, for now I am doing this:
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)方法来做到这一点?
I think both above ways are very similar. I want to know is there a more elegant (pythonic) way to do this?
我首先尝试从 for
循环的内部或外部捕获 StopIteration
,但是我很快意识到,由于 StopIteration
例外是内置 for
循环本身,以下两个代码段均无效
I first tried to catch the StopIteration
from inside or outside of a for
loop, but I soon realize that since the StopIteration
exception is build into for
loop itself, both following code snippet didn't work.
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()
就是这么简单。
这篇关于在python中,如何检查标准输入流(sys.stdin)的结尾并对此做一些特殊的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!