2010-10-31 61 views
2

在C++或任何其他语言中,您可以编写连续从stdin输入行并在每行之后输出结果的程序。喜欢的东西:Python从Stdin无缓冲区读取并输出

while (true) { 
    readline 
    break if eof 

    print process(line) 
} 

我似乎不能,因为它缓冲输出得到这样在Python的行为(即会发生不打印,直到退出循环()?)。因此,程序结束时会打印所有内容。我如何获得与C程序(其中endl刷新)相同的行为。

回答

2

您是否有示例显示问题?

例如(Python 3中):在每行后每行的

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

打印长度。

+1

如果输入是一个终端,Python的标准输入是行缓冲。否则,它包含一个缓冲区。另请参阅:https://stackoverflow.com/questions/3670323/setting-smaller-buffer-size-for-sys-stdin – 2015-12-03 15:11:18

1

Python不应该通过换行符缓冲文本,但如果发生了这种情况,您可以尝试sys.stdout.flush()

+0

注意:只有输出到终端时才为true。否则Python会缓冲输出。所以'sys.stdout.flush()'实际上是如果你需要无缓冲输出到文件的方式。 – 2016-11-30 18:34:59

1

使用sys.stdout.flush()清除打印缓冲区。

import sys 

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

文档:http://docs.python.org/library/sys.html

0
$ cat test.py 
import sys 

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

然后我在终端运行它,并击中后 '123' 输入和 '456'

$ python test.py 
123 
1 
2 
3 


456 
4 
5 
6