I want to run a number of shell commands inside python, and I'd like to have them being outputted on the fly (similar to the way they would come in bash).
To do so I'm using:
import subprocess
cmd='''
x=1
while [ $x -le 5 ]; do
echo "$x"
x=$(( $x + 1 ))
sleep 2
done
'''
out=subprocess.run(cmd,
check=True, shell=True,stdin=PIPE, stdout=PIPE, stderr=STDOUT)
out.stdout
Questions:
- However, I only get the full output when the script ends. Is there a way to get it as it goes?
- In case it is relevant, I actually don't need to get anything from my run (i.e. not going to pipe it or anything.). Should I instead be using
os.system
?