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

(yzsuai) #1

for each directory in an entire tree
upload simple files, recur into subdirectories
"""
localfiles = os.listdir(localdir)
for localname in localfiles:
localpath = os.path.join(localdir, localname)
print('uploading', localpath, 'to', localname, end=' ')
if not os.path.isdir(localpath):
self.uploadOne(localname, localpath, localname)
self.fcount += 1
else:
try:
self.connection.mkd(localname)
print('directory created')
except:
print('directory not created')
self.connection.cwd(localname) # change remote dir
self.uploadDir(localpath) # upload local subdir
self.connection.cwd('..') # change back up
self.dcount += 1
print('directory exited')


if name == 'main':
ftp = UploadAll()
ftp.configTransfer(site='learning-python.com', rdir='training', user='lutz')
ftp.run(transferAct = lambda: ftp.uploadDir(ftp.localdir))
print('Done:', ftp.fcount, 'files and', ftp.dcount, 'directories uploaded.')


Like the flat upload script, this one can be run on any machine with Python and sockets
and upload to any machine running an FTP server; I run it both on my laptop PC and
on other servers by Telnet or SSH to upload sites to my ISP.


The crux of the matter in this script is the os.path.isdir test near the top; if this test
detects a directory in the current local directory, we create an identically named direc-
tory on the remote machine with connection.mkd and descend into it with
connection.cwd, and recur into the subdirectory on the local machine (we have to use
recursive calls here, because the shape and depth of the tree are arbitrary). Like all FTP
object methods, mkd and cwd methods issue FTP commands to the remote server. When
we exit a local subdirectory, we run a remote cwd('..') to climb to the remote parent
directory and continue; the recursive call level’s return restores the prior directory on
the local machine. The rest of the script is roughly the same as the original.


In the interest of space, I’ll leave studying this variant in more depth as a suggested
exercise. For more context, try changing this script so as not to assume that the top-
level remote directory already exists. As usual in software, there are a variety of imple-
mentation and operation options here.


Here is the sort of output displayed on the console when the upload-all script is run,
uploading a site with multiple subdirectory levels which I maintain with site builder
tools. It’s similar to the flat upload (which you might expect, given that it is reusing


894 | Chapter 13: Client-Side Scripting

Free download pdf