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

(yzsuai) #1

################################################################################
"""


import os, sys
listonly = False
textexts = ['.py', '.pyw', '.txt', '.c', '.h'] # ignore binary files


def searcher(startdir, searchkey):
global fcount, vcount
fcount = vcount = 0
for (thisDir, dirsHere, filesHere) in os.walk(startdir):
for fname in filesHere: # do non-dir files here
fpath = os.path.join(thisDir, fname) # fnames have no dirpath
visitfile(fpath, searchkey)


def visitfile(fpath, searchkey): # for each non-dir file
global fcount, vcount # search for string
print(vcount+1, '=>', fpath) # skip protected files
try:
if not listonly:
if os.path.splitext(fpath)[1] not in textexts:
print('Skipping', fpath)
elif searchkey in open(fpath).read():
input('%s has %s' % (fpath, searchkey))
fcount += 1
except:
print('Failed:', fpath, sys.exc_info()[0])
vcount += 1


if name == 'main':
searcher(sys.argv[1], sys.argv[2])
print('Found in %d files, visited %d' % (fcount, vcount))


Operationally, this script works roughly the same as calling its visitfile function for
every result generated by our find.find tool with a pattern of “”; but because this
version is specific to searching content it can better tailored for its goal. Really, this
equivalence holds only because a “
” pattern invokes an exhaustive traversal in
find.find, and that’s all that this new script’s searcher function does. The finder is
good at selecting specific file types, but this script benefits from a more custom single
traversal.


When run standalone, the search key is passed on the command line; when imported,
clients call this module’s searcher function directly. For example, to search (that is,
grep) for all appearances of a string in the book examples tree, I run a command line
like this in a DOS or Unix shell:


C:\\PP4E> Tools\search_all.py. mimetypes
1 => .\LaunchBrowser.py
2 => .\Launcher.py
3 => .\Launch_PyDemos.pyw
4 => .\Launch_PyGadgets_bar.pyw
5 => .\__init__.py
6 => .\__init__.pyc

328 | Chapter 6: Complete System Programs

Free download pdf