Sometimes, we want to write to a Python subprocess’ stdin.
In this article, we’ll look at how to write to a Python subprocess’ stdin.
How to write to a Python subprocess’ stdin?
To write to a Python subprocess’ stdin, we can use the communicate method.
For instance, we write
from subprocess import Popen, PIPE, STDOUT
p = Popen(['myapp'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
stdout_data = p.communicate(input='data_to_write')[0]
to call Popen with the command we want to run in a list.
And we set stdout , stdin, and stderr all to PIPE to pipe them to their default locations.
Next, we call p.communicate with the input argument set to the string we want to write to stdin.
Conclusion
To write to a Python subprocess’ stdin, we can use the communicate method.