4

In C++ or any other languages, you can write programs that continuously take input lines from stdin and output the result after each line. Something like:

while (true) {
   readline
   break if eof

   print process(line)
}

I can't seem to get this kind of behavior in Python because it buffers the output (i.e. no printing will happen until the loop exits (?)). Thus, everything is printed when the program finishes. How do I get the same behavior as with C programs (where endl flushes).

textshell
  • 1,746
  • 14
  • 21
Verhogen
  • 27,221
  • 34
  • 90
  • 109

4 Answers4

3

Do you have an example which shows the problem?

For example (Python 3):

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

Prints the length of each line after each line.

eq-
  • 9,986
  • 36
  • 38
  • 1
    If the input is a terminal, Python's stdin is line-buffered. Otherwise, it includes a buffer. See also: https://stackoverflow.com/questions/3670323/setting-smaller-buffer-size-for-sys-stdin – Denilson Sá Maia Dec 03 '15 at 15:11
2

use sys.stdout.flush() to flush out the print buffer.

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

pyfunc
  • 65,343
  • 15
  • 148
  • 136
1

Python should not buffer text past newlines, but you could try sys.stdout.flush() if that's what is happening.

Gintautas Miliauskas
  • 7,744
  • 4
  • 32
  • 34
  • Note: only true if output is to terminal. Otherwise Python will buffer output. So `sys.stdout.flush()` is in fact the way to go if you need unbuffered output to a file. – Edward Falk Nov 30 '16 at 18:34
0
$ cat test.py
import sys

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

then i run it in terminal and hit Enter after '123' and '456'

$ python test.py 
123
1
2
3


456
4
5
6
seriyPS
  • 6,817
  • 2
  • 25
  • 16