read and process stdin output of another console application
<p>I want to manipulate the output of a console trace tool in a python script. So I want to read each line that the tool writes to stdout and maybe do something with that line and print it to the screen.</p>

<p>I have this script:</p>

<pre><code>import sys

for l in sys.stdin:
    print l
</code></pre>

<p>and I start the trace tool like this:</p>

<pre><code>qspy -c COM7 | my_script.py
</code></pre>

<p>the problem is when I hit enter the first time: nothing happens.  When I hit enter again, I see all the output that was created by the tool but it also quits (the trace-tool quits on any character).  What am I doing wrong?</p>

<p>i'm on windows.</p>

<hr>

<p>EDIT:</p>

<p>I've tried all the suggestions, with little success:</p>

<p>first of all i created this little script to produce some output on stdout:</p>

<pre><code>import time

while 1:
    time.sleep(1)
    print "test"
</code></pre>

<p>this does not work at all (no output):</p>

<pre><code>import sys

for line in sys.stdin:
    print line,
    sys.stdout.flush() 
</code></pre>

<p>this one also doesnt do anything:</p>

<pre><code>import fileinput, sys

for line in fileinput.input():
    print line,
    sys.stdout.flush()
</code></pre>

<p>this one works, but only with the test-script, not with qspy:</p>

<pre><code>import sys

for line in iter(sys.stdin.readline, ''):
    print line,
    sys.stdout.flush()
</code></pre>

<p>i did call the scripts like this:</p>

<pre><code>test.py | python -u my_script.py
</code></pre>

<p>and did also:</p>

<pre><code>set PYTHONUNBUFFERED=1
</code></pre>
