I would like to write a program that can take input piped to it, manipulate it, and output it immediately. It seems that no matter what various things I try (using stdout.write
rather than print
, explicitly flushing stdout
, setting stdin
to be unbuffered), the output seems to be delayed until the input program is closed.
Example input script:
import sys
import time
sys.stdout.write('1\n')
sys.stdout.flush()
time.sleep(3)
sys.stdout.write('2\n')
sys.stdout.flush()
Example output script:
import sys
import time
for line in sys.stdin:
print time.time()
sys.stdout.write(line)
sys.stdout.flush()
If I run this:
python input.py | python output.py
I get something like this:
1428023794.99
1
1428023794.99
2
Clearly the lines are making it to the second program at the same time. I've also tried running the second python script with the -u
flag to unbuffer stdin, but get the same output.
How can I make my program pulling the text from stdin
output the text immediately?