I have a program written in Python that at some point creates a subprocess and then has to get its std output in "real time" through a file (the process takes a while and some output is needed while it is still running). The problem is that, sometimes, a chunk of the output is lost (actually a chunk starting at the begining). The code looks like this:
import subprocess
import tempfile
import time
..
tf_out = tempfile.TemporaryFile()
tf_err = tempfile.TemporaryFile()
tf_in = tempfile.TemporaryFile()
tf_in.write(some_stdin)
tf_in.seek(0)
# create the process
process = subprocess.Popen(command, shell=True,
stdin=tf_in,
stdout=tf_out,
stderr=tf_err)
running = True
while running:
# last iteration if process ended
if process.poll() is not None:
running = False
# read output
tf_out.seek(0) # 1
stdout = tf_out.read() # 2
# do something with the partial output
do_something(stdout)
time.sleep(0.1)
tf_out.close()
tf_err.close()
tf_in.close()
..
I wonder if it is possible that the problem may be between # 1
and # 2
, in case that: the subprocess write something, then seek to zero at # 1
, another write starting at zero because of the seek (wrong one), and finally the read at point # 2
doesn't see the first write. If that's the problem, any idea how to do it?
Thanks in advance!