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

(yzsuai) #1

Technically, passing this script a first argument of 3 runs both a FileVisitor and a
SearchVisitor (two separate traversals are performed). The first argument is really used
as a bit mask to select one or more supported self-tests; if a test’s bit is on in the binary
value of the argument, the test will be run. Because 3 is 011 in binary, it selects both a
search (010) and a listing (001). In a more user-friendly system, we might want to be
more symbolic about that (e.g., check for -search and -list arguments), but bit masks
work just as well for this script’s scope.


As usual, this module can also be used interactively. The following is one way to de-
termine how many files and directories you have in specific directories; the last com-
mand walks over your entire drive (after a generally noticeable delay!). See also the
“biggest file” example at the start of this chapter for issues such as potential repeat visits
not handled by this walker:


C:\...\PP4E\Tools> python
>>> from visitor import FileVisitor
>>> V = FileVisitor(trace=0)
>>> V.run(r'C:\temp\PP3E\Examples')
>>> V.dcount, V.fcount
(186, 1429)

>>> V.run('..') # independent walk (reset counts)
>>> V.dcount, V.fcount
(19, 181)

>>> V.run('..', reset=False) # accumulative walk (keep counts)
>>> V.dcount, V.fcount
(38, 362)

>>> V = FileVisitor(trace=0) # new independent walker (own counts)
>>> V.run(r'C:\\') # entire drive: try '/' on Unix-en
>>> V.dcount, V.fcount
(24992, 198585)

Although the visitor module is useful by itself for listing and searching trees, it was
really designed to be extended. In the rest of this section, let’s quickly step through a
handful of visitor clients which add more specific tree operations, using normal OO
customization techniques.


Editing Files in Directory Trees (Visitor)


After genericizing tree traversals and searches, it’s easy to add automatic file editing in
a brand-new, separate component. Example 6-19 defines a new EditVisitor class that
simply customizes the visitmatch method of the SearchVisitor class to open a text
editor on the matched file. Yes, this is the complete program—it needs to do something
special only when visiting matched files, and so it needs to provide only that behavior.
The rest of the traversal and search logic is unchanged and inherited.


334 | Chapter 6: Complete System Programs

Free download pdf