Reading stdin, stdout, and stderr
The spawned processes can communicate with the operating system in three channels:
- Standard input (
stdin
) - Standard output (
stdout
) - Standard error (
stderr
)
In subprocess, Popen()
can interact with the three channels and redirect each stream to an external file, or to a special value called PIPE
. An additional method, called communicate()
, is used to read from the stdout
and write on the stdin
. The communicate()
method can take input from the user and return both the standard output and the standard error, as shown in the following code snippet:
import subprocess p = subprocess.Popen(["ping", "8.8.8.8", "-c", "3"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout, stderr = p.communicate() print("""==========The Standard Output is========== {}""".format(stdout)) print("""==========The Standard Error is========== {}""".format(stderr))

Similarly, you can send data and write to the process using the input argument inside communicate()
:
import subprocess p =...