is some Python code that runs the two DOS shell commands typed at the shell prompt
shown previously:
C:\...\PP4E\System> python
>>> import os
>>> os.system('dir /B')
helloshell.py
more.py
more.pyc
spam.txt
__init__.py
0
>>> os.system('type helloshell.py')
# a Python program
print('The Meaning of Life')
0
>>> os.system('type hellshell.py')
The system cannot find the file specified.
1
The 0 s at the end of the first two commands here are just the return values of the system
call itself (its exit status; zero generally means success). The system call can be used to
run any command line that we could type at the shell’s prompt (here, C:...\PP4E
\System>). The command’s output normally shows up in the Python session’s or pro-
gram’s standard output stream.
Communicating with shell commands
But what if we want to grab a command’s output within a script? The os.system call
simply runs a shell command line, but os.popen also connects to the standard input or
output streams of the command; we get back a file-like object connected to the com-
mand’s output by default (if we pass a w mode flag to popen, we connect to the com-
mand’s input stream instead). By using this object to read the output of a command
spawned with popen, we can intercept the text that would normally appear in the
console window where a command line is typed:
>>> open('helloshell.py').read()
"# a Python program\nprint('The Meaning of Life')\n"
>>> text = os.popen('type helloshell.py').read()
>>> text
"# a Python program\nprint('The Meaning of Life')\n"
>>> listing = os.popen('dir /B').readlines()
>>> listing
['helloshell.py\n', 'more.py\n', 'more.pyc\n', 'spam.txt\n', '__init__.py\n']
Here, we first fetch a file’s content the usual way (using Python files), then as the output
of a shell type command. Reading the output of a dir command lets us get a listing of
files in a directory that we can then process in a loop. We’ll learn other ways to obtain
such a list in Chapter 4; there we’ll also learn how file iterators make the readlines call
96 | Chapter 2: System Tools