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

(yzsuai) #1

For my purposes, that’s often a reasonable constraint. I avoid nested subdirectories to
keep things simple, and I store my book support home website as a simple directory of
files. For other sites, though, including one I keep at another machine, site transfer
scripts are easier to use if they also automatically transfer subdirectories along the way.


Uploading Local Trees


It turns out that supporting directories on uploads is fairly simple—we need to add
only a bit of recursion and remote directory creation calls. The upload script in Exam-
ple 13-15 extends the class-based version we just saw in Example 13-14, to handle
uploading all subdirectories nested within the transferred directory. Furthermore, it
recursively transfers subdirectories within subdirectories—the entire directory tree
contained within the top-level transfer directory is uploaded to the target directory at
the remote server.


In terms of its code structure, Example 13-15 is just a customization of the FtpTools
class of the prior section—really, we’re just adding a method for recursive uploads, by
subclassing. As one consequence, we get tools such as parameter configuration, content
type testing, and connection and upload code for free here; with OOP, some of the
work is done before we start.


Example 13-15. PP4E\Internet\Ftp\Mirror\uploadall.py


#!/bin/env python
"""
############################################################################
extend the FtpTools class to upload all files and subdirectories from a
local dir tree to a remote site/dir; supports nested dirs too, but not
the cleanall option (that requires parsing FTP listings to detect remote
dirs: see cleanall.py); to upload subdirectories, uses os.path.isdir(path)
to see if a local file is really a directory, FTP().mkd(path) to make dirs
on the remote machine (wrapped in a try in case it already exists there),
and recursion to upload all files/dirs inside the nested subdirectory.
############################################################################
"""


import os, ftptools


class UploadAll(ftptools.FtpTools):
"""
upload an entire tree of subdirectories
assumes top remote directory exists
"""
def init(self):
self.fcount = self.dcount = 0


def getcleanall(self):
return False # don't even ask


def uploadDir(self, localdir):
"""


Transferring Directory Trees with ftplib | 893
Free download pdf