在python中,如何检查标准输入流(sys.stdin)的结尾并对此做一些特殊的事情

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24089090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:57:13  来源:igfitidea点击:

In python, how to check the end of standard input streams (sys.stdin) and do something special on that

pythonstdineof

提问by YaOzI

I want to do something like:

我想做类似的事情:

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

Or with this:

或者用这个:

while True:
    line = sys.stdin.readline()
    if not line:
        print 'EOF!'
        break
    print line,

I think both above ways are very similar. I want to know is there a more elegant (pythonic) way to do this?

我认为上述两种方式都非常相似。我想知道有没有更优雅(pythonic)的方法来做到这一点?



Early failed tries:

早期失败的尝试:

I first tried to catch the StopIterationfrom inside or outside of a forloop, but I soon realize that since the StopIterationexception is build intoforloop itself, both following code snippet didn't work.

我首先尝试StopIterationfor循环内部或外部捕获,但我很快意识到,由于StopIteration异常已构建到for循环本身中,因此以下代码段均无效。

try:
    for line in sys.stdin:
        print line,
except StopIteration:
    print 'EOF'

or

或者

for line in sys.stdin:
    try:
        print line,
    except StopIteration:
        print 'EOF'

采纳答案by user2357112 supports Monica

for line in sys.stdin:
    do_whatever()
# End of stream!
do_whatever_else()

It's that simple.

就这么简单。

回答by KIM Taegyoon

Use try/except. Input

使用尝试/除外。输入

When EOF is read, EOFError is raised.

读取 EOF 时,会引发 EOFError。

while True:
    try:
        s=input("> ")
    except EOFError:
        print("EOF")
        break