In fact, we can use obtain both the input and output streams of a spawned program with
this module. Let’s reuse the simple writer and reader scripts we wrote earlier to
demonstrate:
C:\...\PP4E\System\Streams> type writer.py
print("Help! Help! I'm being repressed!")
print(42)
C:\...\PP4E\System\Streams> type reader.py
print('Got this: "%s"' % input())
import sys
data = sys.stdin.readline()[:-1]
print('The meaning of life is', data, int(data) * 2)
Code like the following can both read from and write to the reader script—the pipe
object has two file-like objects available as attached attributes, one connecting to the
input stream, and one to the output (Python 2.X users might recognize these as equiv-
alent to the tuple returned by the now-defunct os.popen2):
>>> pipe = Popen('python reader.py', stdin=PIPE, stdout=PIPE)
>>> pipe.stdin.write(b'Lumberjack\n')
11
>>> pipe.stdin.write(b'12\n')
3
>>> pipe.stdin.close()
>>> output = pipe.stdout.read()
>>> pipe.wait()
0
>>> output
b'Got this: "Lumberjack"\r\nThe meaning of life is 12 24\r\n'
As we’ll learn in Chapter 5, we have to be cautious when talking back and forth to a
program like this; buffered output streams can lead to deadlock if writes and reads are
interleaved, and we may eventually need to consider tools like the Pexpect utility as a
workaround (more on this later).
Finally, even more exotic stream control is possible—the following connects two pro-
grams, by piping the output of one Python script into another, first with shell syntax,
and then with the subprocess module:
C:\...\PP4E\System\Streams> python writer.py | python reader.py
Got this: "Help! Help! I'm being repressed!"
The meaning of life is 42 84
C:\...\PP4E\System\Streams> python
>>> from subprocess import Popen, PIPE
>>> p1 = Popen('python writer.py', stdout=PIPE)
>>> p2 = Popen('python reader.py', stdin=p1.stdout, stdout=PIPE)
>>> output = p2.communicate()[0]
>>> output
b'Got this: "Help! Help! I\'m being repressed!"\r\nThe meaning of life is 42 84\r\n'
>>> p2.returncode
0
Standard Streams | 131