Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Read and Output from Stdin Unbuffered

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).

like image 392
Verhogen Avatar asked Sep 12 '25 11:09

Verhogen


2 Answers

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.

like image 122
eq- Avatar answered Sep 15 '25 00:09

eq-


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

like image 20
pyfunc Avatar answered Sep 15 '25 02:09

pyfunc