Reading stdin, stdout, and stderr

The spawned processes can communicate with the operating system in three channels:

  1. Standard input (stdin)
  2. Standard output (stdout)
  3. 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 subprocessp = subprocess.Popen(["ping", "8.8.8.8", "-c", "3"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)stdout, stderr = p.communicate()print("""==========The ...

Get Hands-On Enterprise Automation with Python. now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.