在 Python 中,如何检查标准输入流 (sys.stdin) 的结束并执行特殊操作

18 投票
3 回答
43867 浏览
提问于 2025-04-18 08:54

我想做一些类似这样的事情:

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,

我觉得上面这两种方法很相似。我想知道有没有更优雅(更符合Python风格)的方法来实现这个?


早期失败的尝试:

我最开始尝试在for循环的内部或外部捕获StopIteration,但我很快意识到,由于StopIteration异常是内置于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'

3 个回答

0

使用迭代器

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()
15

使用try/except来处理错误。输入的时候,如果遇到文件结束符(EOF),就会出现EOFError这个错误。

while True:
    try:
        s=input("> ")
    except EOFError:
        print("EOF")
        break
30
for line in sys.stdin:
    do_whatever()
# End of stream!
do_whatever_else()

就这么简单。

撰写回答