2

How to receive data from the environment e.g. bash

I am trying to launch two Python scripts in bash and pipe stdout from one of them to stdin of the other. The first script outputs a single number every second.

./script1 | ./script2
./script1 > ~/file &; tail -f ~/file

I tried those, but can't get it working. script1 outputs via Python's print, while script2 is tested with echo "21.11 22.23 33.233" | ./script2 and is known to work.

If I terminate script1 ofter some time, and then cat ~/file, I see the actual data. However, at the time of execution, neither of the above examples work.

How do I make this work? I would like to be able to work both with and without intermediate file.

1
  • 1
    you have to flush the output buffer Commented Jan 14, 2014 at 5:22

1 Answer 1

2

In the python script make sure you call:

sys.stdout.flush()

after print-ing. You don't have to do that on each statement, but you have to do it on each group of prints that has to be processed. ( import sys if not done yet).

3
  • Why is that. In the question that I linked to, it is discussed if there is a better way to output data than print. So is there (it's only one print per iteration)?
    – Vorac
    Commented Jan 14, 2014 at 10:25
  • That question is about reading data from stdin, not printing (which writing to sys.stdout)
    – Timo
    Commented Jan 14, 2014 at 10:34
  • Secondly, is print i a proper way to stream data to the environment?
    – Vorac
    Commented Jan 14, 2014 at 10:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .