Redirecting input or output with os.popen
In fact, by passing in the desired mode flag, we redirect either a spawned program’s
output or input streams to a file in the calling scripts, and we can obtain the spawned
program’s exit status code from the close method (None means “no error” here). To
illustrate, consider the following two scripts:
C:\...\PP4E\System\Streams> type hello-out.py
print('Hello shell world')
C:\...\PP4E\System\Streams> type hello-in.py
inp = input()
open('hello-in.txt', 'w').write('Hello ' + inp + '\n')
These scripts can be run from a system shell window as usual:
C:\...\PP4E\System\Streams> python hello-out.py
Hello shell world
C:\...\PP4E\System\Streams> python hello-in.py
Brian
C:\...\PP4E\System\Streams> type hello-in.txt
Hello Brian
As we saw in the prior chapter, Python scripts can read output from other programs
and scripts like these, too, using code like the following:
C:\...\PP4E\System\Streams> python
>>> import os
>>> pipe = os.popen('python hello-out.py') # 'r' is default--read stdout
>>> pipe.read()
'Hello shell world\n'
>>> print(pipe.close()) # exit status: None is good
None
But Python scripts can also provide input to spawned programs’ standard input
streams—passing a “w” mode argument, instead of the default “r”, connects the re-
turned object to the spawned program’s input stream. What we write on the spawning
end shows up as input in the program started:
>>> pipe = os.popen('python hello-in.py', 'w') # 'w'--write to program stdin
>>> pipe.write('Gumby\n')
6
>>> pipe.close() # \n at end is optional
>>> open('hello-in.txt').read() # output sent to a file
'Hello Gumby\n'
The popen call is also smart enough to run the command string as an independent
process on platforms that support such a notion. It accepts an optional third argument
that can be used to control buffering of written text, which we’ll finesse here.
Standard Streams | 129