I've been reading SO discussion on how output going to a terminal is line buffered, and output to pipes or files etc is usually "block buffered". I am trying the following two pipelines on OSX, which aim to prepend a timestamp to the incoming lines:
while [ 1 ] ; do echo $RANDOM && sleep .5 ; done | ~/bin/prepend_ts_python
and
while [ 1 ] ; do echo $RANDOM && sleep .5 ; done | ~/bin/prepend_ts_perl
The Perl program is (and I don't know much about Perl):
#!/usr/bin/perl
while ( <> ) {
print scalar(localtime()), " ";
print;
}
The Python program (clearly not prepending a timestamp yet) is:
#!/usr/bin/python
import sys
for line in sys.stdin:
print("foo")
The pipeline using the Perl version prints output immediately, as desired, whereas the Python one outputs intermittently.
I was under the impression that any buffering that was going on was being determined by the while
/echo
loop, and for this reason people were recommending using the unbuffer
command on the beginning of the pipeline.
Does Perl have some way of flushing its STDIN? I didn't think it could reach "backwards" in the pipeline. Why are they different?