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

(yzsuai) #1

filetext = template.replace('$server$', servername) # insert text
filetext = filetext.replace('$home$', homedir) # and write
filetext = filetext.replace('$file$', filename) # file varies
open(fwdname, 'w').write(filetext)
count += 1


print('Last file =>\n', filetext, sep='')
print('Done:', count, 'forward files created.')


Notice that the template’s text is loaded by reading a file; it would work just as well to
code it as an imported Python string variable (e.g., a triple-quoted string in a module
file). Also observe that all configuration options are assignments at the top of the
script, not command-line arguments; since they change so seldom, it’s convenient to
type them just once in the script itself.


But the main thing worth noticing here is that this script doesn’t care what the template
file looks like at all; it simply performs global substitutions blindly in its text, with a
different filename value for each generated file. In fact, we can change the template file
any way we like without having to touch the script. Though a fairly simple technique,
such a division of labor can be used in all sorts of contexts—generating “makefiles,”
form letters, HTML replies from CGI scripts on web servers, and so on. In terms of
library tools, the generator script:



  • Uses os.listdir to step through all the filenames in the site’s directory
    (glob.glob would work too, but may require stripping directory prefixes from file
    names)

  • Uses the string object’s replace method to perform global search-and-replace op-
    erations that fill in the $-delimited targets in the template file’s text, and endswith
    to skip non-HTML files (e.g., images—most browsers won’t know what to do with
    HTML text in a “.jpg” file)

  • Uses os.path.join and built-in file objects to write the resulting text out to a
    forward-link file of the same name in an output directory


The end result is a mirror image of the original website directory, containing only
forward-link files generated from the page template. As an added bonus, the generator
script can be run on just about any Python platform—I can run it on my Windows
laptop (where I’m writing this book), as well as on a Linux server (where my http://
learning-python.com domain is hosted). Here it is in action on Windows:


C:\...\PP4E\System\Filetools> python site-forward.py
creating about-lp.html as C:\temp\isp-forward\about-lp.html
creating about-lp1e.html as C:\temp\isp-forward\about-lp1e.html
creating about-lp2e.html as C:\temp\isp-forward\about-lp2e.html
creating about-lp3e.html as C:\temp\isp-forward\about-lp3e.html
creating about-lp4e.html as C:\temp\isp-forward\about-lp4e.html
...many more lines deleted...
creating training.html as C:\temp\isp-forward\training.html
creating whatsnew.html as C:\temp\isp-forward\whatsnew.html

Generating Redirection Web Pages| 295
Free download pdf