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

(yzsuai) #1

This is both wildly powerful and dangerous. If the string to be replaced can show up
in places you didn’t anticipate, you might just ruin an entire tree of files by running the
ReplaceVisitor object defined here. On the other hand, if the string is something very
specific, this object can obviate the need to manually edit suspicious files. For instance,
website addresses in HTML files are likely too specific to show up in other places by
chance.


Counting Source Code Lines (Visitor)


The two preceding visitor module clients were both search-oriented, but it’s just as
easy to extend the basic walker class for more specific goals. Example 6-21, for instance,
extends FileVisitor to count the number of lines in program source code files of various
types throughout an entire tree. The effect is much like calling the visitfile method
of this class for each filename returned by the find tool we wrote earlier in this chapter,
but the OO structure here is arguably more flexible and extensible.


Example 6-21. PP4E\Tools\visitor_sloc.py


"""
Count lines among all program source files in a tree named on the command
line, and report totals grouped by file types (extension). A simple SLOC
(source lines of code) metric: skip blank and comment lines if desired.
"""


import sys, pprint, os
from visitor import FileVisitor


class LinesByType(FileVisitor):
srcExts = [] # define in subclass


def init(self, trace=1):
FileVisitor.init(self, trace=trace)
self.srcLines = self.srcFiles = 0
self.extSums = {ext: dict(files=0, lines=0) for ext in self.srcExts}


def visitsource(self, fpath, ext):
if self.trace > 0: print(os.path.basename(fpath))
lines = len(open(fpath, 'rb').readlines())
self.srcFiles += 1
self.srcLines += lines
self.extSums[ext]['files'] += 1
self.extSums[ext]['lines'] += lines


def visitfile(self, filepath):
FileVisitor.visitfile(self, filepath)
for ext in self.srcExts:
if filepath.endswith(ext):
self.visitsource(filepath, ext)
break


class PyLines(LinesByType):
srcExts = ['.py', '.pyw'] # just python files


338 | Chapter 6: Complete System Programs

Free download pdf