Sometimes, we want to read streaming input from Python subprocess.communicate()
method.
In this article, we’ll look at how to read streaming input from Python subprocess.communicate()
method.
How to read streaming input from Python subprocess.communicate()?
To read streaming input from Python subprocess.communicate()
method, we can use the subprocess.Popen
method.
For instance, we write:
from subprocess import Popen, PIPE
with Popen(["ls", "-l"], stdout=PIPE, bufsize=1,
universal_newlines=True) as p:
for line in p.stdout:
print(line, end='')
We call Popen
with the command and argument in the list.
And we set stdout
to PIPE
to pipe the output to p.stdout
.
Then we loop through each line in p.stdout
and print them with print
.
Conclusion
To read streaming input from Python subprocess.communicate()
method, we can use the subprocess.Popen
method.