Sometimes, we want to get real time output using subprocess with Python.
In this article, we’ll look at how to get real time output using subprocess with Python.
How to get real time output using subprocess with Python?
To get real time output using subprocess with Python, we loop through the lines that are returned with the iterator that we get with stdout.readline
.
For instance, we write
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1)
for line in iter(p.stdout.readline, b''):
print(line)
p.stdout.close()
p.wait()
to call Popen
with the cmd
command string to run.
And we set stdout
to subprocess.PIPE
and bufsize
to 1 to get the output.
Then we show the output with
for line in iter(p.stdout.readline, b''):
print(line)
And then we call close
to stop reading from stdout.
Conclusion
To get real time output using subprocess with Python, we loop through the lines that are returned with the iterator that we get with stdout.readline
.