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

(yzsuai) #1

To get rid of all the files accidentally uploaded, I quickly wrote the script in Exam-
ple 13-16 in emergency (really, panic) mode; it deletes all files and nested subdirectories
in an entire remote tree. Luckily, this was very easy to do given all the reuse that
Example 13-16 inherits from the FtpTools superclass. Here, we just have to define the
extension for recursive remote deletions. Even in tactical mode like this, OOP can be
a decided advantage.


Example 13-16. PP4E\Internet\Ftp\Mirror\cleanall.py


#!/bin/env python
"""
##############################################################################
extend the FtpTools class to delete files and subdirectories from a remote
directory tree; supports nested directories too; depends on the dir()
command output format, which may vary on some servers! - see Python's
Tools\Scripts\ftpmirror.py for hints; extend me for remote tree downloads;
##############################################################################
"""


from ftptools import FtpTools


class CleanAll(FtpTools):
"""
delete an entire remote tree of subdirectories
"""
def init(self):
self.fcount = self.dcount = 0


def getlocaldir(self):
return None # irrelevent here


def getcleanall(self):
return True # implied here


def cleanDir(self):
"""
for each item in current remote directory,
del simple files, recur into and then del subdirectories
the dir() ftp call passes each line to a func or method
"""
lines = [] # each level has own lines
self.connection.dir(lines.append) # list current remote dir
for line in lines:
parsed = line.split() # split on whitespace
permiss = parsed[0] # assume 'drw... ... filename'
fname = parsed[-1]
if fname in ('.', '..'): # some include cwd and parent
continue
elif permiss[0] != 'd': # simple file: delete
print('file', fname)
self.connection.delete(fname)
self.fcount += 1
else: # directory: recur, del
print('directory', fname)


896 | Chapter 13: Client-Side Scripting

Free download pdf