part of the book, let’s take a quick first look at the basics here. Two os functions allow
scripts to run any command line that you can type in a console window:
os.system
Runs a shell command from a Python script
os.popen
Runs a shell command and connects to its input or output streams
In addition, the relatively new subprocess module provides finer-grained control over
streams of spawned shell commands and can be used as an alternative to, and even for
the implementation of, the two calls above (albeit with some cost in extra code
complexity).
What’s a shell command?
To understand the scope of the calls listed above, we first need to define a few terms.
In this text, the term shell means the system that reads and runs command-line strings
on your computer, and shell command means a command-line string that you would
normally enter at your computer’s shell prompt.
For example, on Windows, you can start an MS-DOS console window (a.k.a. “Com-
mand Prompt”) and type DOS commands there—commands such as dir to get a di-
rectory listing, type to view a file, names of programs you wish to start, and so on. DOS
is the system shell, and commands such as dir and type are shell commands. On Linux
and Mac OS X, you can start a new shell session by opening an xterm or terminal
window and typing shell commands there too—ls to list directories, cat to view files,
and so on. A variety of shells are available on Unix (e.g., csh, ksh), but they all read and
run command lines. Here are two shell commands typed and run in an MS-DOS console
box on Windows:
C:\...\PP4E\System> dir /B ...type a shell command line
helloshell.py ...its output shows up here
more.py ...DOS is the shell on Windows
more.pyc
spam.txt
__init__.py
C:\...\PP4E\System> type helloshell.py
# a Python program
print('The Meaning of Life')
Running shell commands
None of this is directly related to Python, of course (despite the fact that Python
command-line scripts are sometimes confusingly called “shell tools”). But because the
os module’s system and popen calls let Python scripts run any sort of command that the
underlying system shell understands, our scripts can make use of every command-line
tool available on the computer, whether it’s coded in Python or not. For example, here
Introducing the os Module | 95