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

(yzsuai) #1

class SourceLines(LinesByType):
srcExts = ['.py', '.pyw', '.cgi', '.html', '.c', '.cxx', '.h', '.i']


if name == 'main':
walker = SourceLines()
walker.run(sys.argv[1])
print('Visited %d files and %d dirs' % (walker.fcount, walker.dcount))
print('-'*80)
print('Source files=>%d, lines=>%d' % (walker.srcFiles, walker.srcLines))
print('By Types:')
pprint.pprint(walker.extSums)


print('\nCheck sums:', end=' ')
print(sum(x['lines'] for x in walker.extSums.values()), end=' ')
print(sum(x['files'] for x in walker.extSums.values()))


print('\nPython only walk:')
walker = PyLines(trace=0)
walker.run(sys.argv[1])
pprint.pprint(walker.extSums)


When run as a script, we get trace messages during the walk (omitted here to save
space), and a report with line counts grouped by file type. Run this on trees of your
own to watch its progress; my tree has 907 source files and 48K source lines, including
783 files and 34K lines of “.py” Python code:


C:\...\PP4E\Tools> visitor_sloc.py C:\temp\PP3E\Examples
Visited 1429 files and 186 dirs
--------------------------------------------------------------------------------
Source files=>907, lines=>48047
By Types:
{'.c': {'files': 45, 'lines': 7370},
'.cgi': {'files': 5, 'lines': 122},
'.cxx': {'files': 4, 'lines': 2278},
'.h': {'files': 7, 'lines': 297},
'.html': {'files': 48, 'lines': 2830},
'.i': {'files': 4, 'lines': 49},
'.py': {'files': 783, 'lines': 34601},
'.pyw': {'files': 11, 'lines': 500}}

Check sums: 48047 907

Python only walk:
{'.py': {'files': 783, 'lines': 34601}, '.pyw': {'files': 11, 'lines': 500}}

Recoding Copies with Classes (Visitor)


Let’s peek at one more visitor use case. When I first wrote the cpall.py script earlier in
this chapter, I couldn’t see a way that the visitor class hierarchy we met earlier would
help. Two directories needed to be traversed in parallel (the original and the copy), and
visitor is based on walking just one tree with os.walk. There seemed no easy way to
keep track of where the script was in the copy directory.


Visitor: Walking Directories “++” | 339
Free download pdf