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

(yzsuai) #1

This version accomplishes roughly the same goal as the original, but it has made a few
assumptions to keep the code simple. The “to” directory is assumed not to exist initially,
and exceptions are not ignored along the way. Here it is copying the book examples
tree from the prior edition again on Windows:


C:\...\PP4E\Tools> set PYTHONPATH
PYTHONPATH=C:\Users\Mark\Stuff\Books\4E\PP4E\dev\Examples

C:\...\PP4E\Tools> rmdir /S copytemp
copytemp, Are you sure (Y/N)? y

C:\...\PP4E\Tools> visitor_cpall.py C:\temp\PP3E\Examples copytemp
Copying...
Copied 1429 files, 186 directories in 11.1722033777 seconds

C:\...\PP4E\Tools> fc /B copytemp\PP3E\Launcher.py
C:\temp\PP3E\Examples\PP3E\Launcher.py
Comparing files COPYTEMP\PP3E\Launcher.py and C:\TEMP\PP3E\EXAMPLES\PP3E\LAUNCHER.PY
FC: no differences encountered

Despite the extra string slicing going on, this version seems to run just as fast as the
original (the actual difference can be chalked up to system load variations). For tracing
purposes, this version also prints all the “from” and “to” copy paths during the traversal
if you pass in a third argument on the command line:


C:\...\PP4E\Tools> rmdir /S copytemp
copytemp, Are you sure (Y/N)? y

C:\...\PP4E\Tools> visitor_cpall.py C:\temp\PP3E\Examples copytemp 1
Copying...
d C:\temp\PP3E\Examples => copytemp\
f C:\temp\PP3E\Examples\README-root.txt => copytemp\README-root.txt
d C:\temp\PP3E\Examples\PP3E => copytemp\PP3E
...more lines omitted: try this on your own for the full output...

Other Visitor Examples (External)


Although the visitor is widely applicable, we don’t have space to explore additional
subclasses in this book. For more example clients and use cases, see the following
examples in book’s examples distribution package described in the Preface:



  • Tools\visitor_collect.py collects and/or prints files containing a search string

  • Tools\visitor_poundbang.py replaces directory paths in “#!” lines at the top of Unix
    scripts

  • Tools\visitor_cleanpyc.py is a visitor-based recoding of our earlier bytecode cleanup
    scripts

  • Tools\visitor_bigpy.py is a visitor-based version of the “biggest file” example at the
    start of this chapter


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