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

(yzsuai) #1

self.dcount += 1 # override or extend me
if self.trace > 0: print(dirpath, '...')


def visitfile(self, filepath): # called for each file
self.fcount += 1 # override or extend me
if self.trace > 1: print(self.fcount, '=>', filepath)


class SearchVisitor(FileVisitor):
"""
Search files at and below startDir for a string;
subclass: redefine visitmatch, extension lists, candidate as needed;
subclasses can use testexts to specify file types to search (but can
also redefine candidate to use mimetypes for text content: see ahead)
"""


skipexts = []
testexts = ['.txt', '.py', '.pyw', '.html', '.c', '.h'] # search these exts
#skipexts = ['.gif', '.jpg', '.pyc', '.o', '.a', '.exe'] # or skip these exts


def init(self, searchkey, trace=2):
FileVisitor.init(self, searchkey, trace)
self.scount = 0


def reset(self): # on independent walks
self.scount = 0


def candidate(self, fname): # redef for mimetypes
ext = os.path.splitext(fname)[1]
if self.testexts:
return ext in self.testexts # in test list
else: # or not in skip list
return ext not in self.skipexts


def visitfile(self, fname): # test for a match
FileVisitor.visitfile(self, fname)
if not self.candidate(fname):
if self.trace > 0: print('Skipping', fname)
else:
text = open(fname).read() # 'rb' if undecodable
if self.context in text: # or text.find() != −1
self.visitmatch(fname, text)
self.scount += 1


def visitmatch(self, fname, text): # process a match
print('%s has %s' % (fname, self.context)) # override me lower


if name == 'main':


self-test logic


dolist = 1
dosearch = 2 # 3=do list and search
donext = 4 # when next test added


def selftest(testmask):


332 | Chapter 6: Complete System Programs

Free download pdf