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

(yzsuai) #1


[http://$server$/$home$/$file$
](http://$server$/$home$/$file$)

Please click on the new address to jump to this page, and
update any links accordingly. You will be redirectly shortly.





To fully understand this template, you have to know something about HTML, a web
page description language that we’ll explore in Part IV. But for the purposes of this
example, you can ignore most of this file and focus on just the parts surrounded by
dollar signs: the strings $server$, $home$, and $file$ are targets to be replaced with real
values by global text substitutions. They represent items that vary per site relocation
and file.


Page Generator Script


Now, given a page template file, the Python script in Example 6-8 generates all the
required forward-link files automatically.


Example 6-8. PP4E\System\Filetools\site-forward.py


"""
################################################################################
Create forward-link pages for relocating a web site.
Generates one page for every existing site html file; upload the generated
files to your old web site. See ftplib later in the book for ways to run
uploads in scripts either after or during page file creation.
################################################################################
"""


import os
servername = 'learning-python.com' # where site is relocating to
homedir = 'books' # where site will be rooted
sitefilesdir = r'C:\temp\public_html' # where site files live locally
uploaddir = r'C:\temp\isp-forward' # where to store forward files
templatename = 'template.html' # template for generated pages


try:
os.mkdir(uploaddir) # make upload dir if needed
except OSError: pass


template = open(templatename).read() # load or import template text
sitefiles = os.listdir(sitefilesdir) # filenames, no directory prefix


count = 0
for filename in sitefiles:
if filename.endswith('.html') or filename.endswith('.htm'):
fwdname = os.path.join(uploaddir, filename)
print('creating', filename, 'as', fwdname)


294 | Chapter 6: Complete System Programs

Free download pdf