Python从标准输入读取和输出的无缓冲方式

4

在C++或其他编程语言中,您可以编写连续从标准输入读取输入行并在每行后输出结果的程序。示例如下:

while (true) {
   readline
   break if eof

   print process(line)
}

我似乎无法在Python中获得这种行为,因为它会缓冲输出(即直到循环结束才会发生打印操作)。因此,当程序完成时,所有内容都会被打印出来。我该如何获得与C程序相同的行为(其中endl刷新缓冲区)?

4个回答

3

您是否有一个能够展示问题的例子?

例如(Python 3):

def process(line):
    return len(line)
try:
    while True:
        line = input()
        print(process(line))
except EOFError:
    pass

在每行后打印每行的长度。


1
如果输入是终端,则Python的stdin是行缓冲的。否则,它包括一个缓冲区。另请参阅:https://dev59.com/D3A65IYBdhLWcg3wuRF8 - Denilson Sá Maia

2
使用sys.stdout.flush()来刷新打印缓冲区。
import sys

while True:
    input = raw_input("Provide input to process")
    # process input
    print process(input)
    sys.stdout.flush()

Docs : http://docs.python.org/library/sys.html


1

Python不应该在换行符之后缓存文本,但如果出现这种情况,您可以尝试使用sys.stdout.flush()


注意:只有在输出到终端时才为真。否则,Python会缓冲输出。因此,如果您需要将未缓冲的输出写入文件,则sys.stdout.flush()实际上是正确的方法。 - Edward Falk

0
$ cat test.py
import sys

while True:
    print sys.stdin.read(1)

然后我在终端中运行它,在输入'123'和'456'后按Enter键

$ python test.py 
123
1
2
3


456
4
5
6

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接