I'm using a pretty basic setup with subprocess.Popen() and directing stdout to a variable which I later return to a different part of my python script.
Here is my basic Popen code:
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# wait for the process to terminate
out, err = process.communicate()
errcode = process.returncode
print out
This works great for many basic use cases like ls -al
or similar. However, I am wondering how to handle getting output regularly and consistently from a longer (or indefinitely) running process such as tail -f foo.log
. Is there a way to periodically read stdout in a loop? Or spawn a thread to check and return each on periodically? What is the best approach here?
Thanks!