I'm running a certain bash script via subprocess.Popen
. This is a simplified version of the script:
#!/usr/bin/env bash
echo "I want to read this"
echo "And also this"
echo "Maybe even this"
while :; do
sleep 100
echo "But probably not this"
done
I'd like to obtain its output after running it, before it concludes. I need to do this without using 3rd-party libraries. I've tried a bunch of solutions such as this one or this one. However, none of these solutions worked for me (they all hang when they reach the end of the output). What I have currently is this:
from subprocess import Popen, PIPE, TimeoutExpired
with Popen(['./script.sh'], stdout=PIPE, stderr=PIPE) as process:
try:
output, _ = process.communicate(timeout=5)
except TimeoutExpired:
pass
return process, output
However, this obviously also doesn't capture the output, since the TimeoutExpired
exception is raised before assigning to output
. How would I obtain everything that is currently in the output stream and then continue with the execution of my Python program?