[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

Python Versus csh


If you are familiar with other common shell script languages, it might be useful to see
how Python compares. Here is a simple script in a Unix shell language called csh that
mails all the files in the current working directory with a suffix of .py (i.e., all Python
source files) to a hopefully fictitious address:


#!/bin/csh
foreach x (*.py)
echo $x
mail [email protected] -s $x < $x
end

An equivalent Python script looks similar:


#!/usr/bin/python
import os, glob
for x in glob.glob('*.py'):
print(x)
os.system('mail [email protected] -s %s < %s' % (x, x))

but is slightly more verbose. Since Python, unlike csh, isn’t meant just for shell scripts,
system interfaces must be imported and called explicitly. And since Python isn’t just a
string-processing language, character strings must be enclosed in quotes, as in C.


Although this can add a few extra keystrokes in simple scripts like this, being a general-
purpose language makes Python a better tool once we leave the realm of trivial pro-
grams. We could, for example, extend the preceding script to do things like transfer
files by FTP, pop up a GUI message selector and status bar, fetch messages from an
SQL database, and employ COM objects on Windows, all using standard Python tools.


Python scripts also tend to be more portable to other platforms than csh. For instance,
if we used the Python SMTP interface module to send mail instead of relying on a Unix
command-line mail tool, the script would run on any machine with Python and an
Internet link (as we’ll see in Chapter 13, SMTP requires only sockets). And like C, we
don’t need $ to evaluate variables; what else would you expect in a free language?


Standard Streams | 133
Free download pdf