相关疑难解决方法(0)

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

我想做的事情如下:

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)的方式吗?


早期尝试失败:

我首先尝试StopIterationfor循环内部或外部捕获,但我很快意识到,由于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)

python stdin eof

12
推荐指数
2
解决办法
2万
查看次数

标签 统计

eof ×1

python ×1

stdin ×1