in the os.popen example above unnecessary in most programs, except to display the
list interactively as we did here (see also “subprocess, os.popen, and Itera-
tors” on page 101 for more on the subject).
So far, we’ve run basic DOS commands; because these calls can run any command line
that we can type at a shell prompt, they can also be used to launch other Python scripts.
Assuming your system search path is set to locate your Python (so that you can use the
shorter “python” in the following instead of the longer “C:\Python31\python”):
>>> os.system('python helloshell.py') # run a Python program
The Meaning of Life
0
>>> output = os.popen('python helloshell.py').read()
>>> output
'The Meaning of Life\n'
In all of these examples, the command-line strings sent to system and popen are hard-
coded, but there’s no reason Python programs could not construct such strings at
runtime using normal string operations (+, %, etc.). Given that commands can be dy-
namically built and run this way, system and popen turn Python scripts into flexible and
portable tools for launching and orchestrating other programs. For example, a Python
test “driver” script can be used to run programs coded in any language (e.g., C++, Java,
Python) and analyze their output. We’ll explore such a script in Chapter 6. We’ll also
revisit os.popen in the next chapter in conjunction with stream redirection; as we’ll find,
this call can also send input to programs.
The subprocess module alternative
As mentioned, in recent releases of Python the subprocess module can achieve the same
effect as os.system and os.popen; it generally requires extra code but gives more control
over how streams are connected and used. This becomes especially useful when streams
are tied in more complex ways.
For example, to run a simple shell command like we did with os.system earlier, this
new module’s call function works roughly the same (running commands like “type”
that are built into the shell on Windows requires extra protocol, though normal exe-
cutables like “python” do not):
>>> import subprocess
>>> subprocess.call('python helloshell.py') # roughly like os.system()
The Meaning of Life
0
>>> subprocess.call('cmd /C "type helloshell.py"') # built-in shell cmd
# a Python program
print('The Meaning of Life')
0
>>> subprocess.call('type helloshell.py', shell=True) # alternative for built-ins
# a Python program
print('The Meaning of Life')
0
Introducing the os Module | 97