Example 6-19. PP4E\Tools\visitor_edit.py
"""
Use: "python ...\Tools\visitor_edit.py string rootdir?".
Add auto-editor startup to SearchVisitor in an external subclass component;
Automatically pops up an editor on each file containing string as it traverses;
can also use editor='edit' or 'notepad' on Windows; to use texteditor from
later in the book, try r'python Gui\TextEditor\textEditor.py'; could also
send a search command to go to the first match on start in some editors;
"""
import os, sys
from visitor import SearchVisitor
class EditVisitor(SearchVisitor):
"""
edit files at and below startDir having string
"""
editor = r'C:\cygwin\bin\vim-nox.exe' # ymmv!
def visitmatch(self, fpathname, text):
os.system('%s %s' % (self.editor, fpathname))
if name == 'main':
visitor = EditVisitor(sys.argv[1])
visitor.run('.' if len(sys.argv) < 3 else sys.argv[2])
print('Edited %d files, visited %d' % (visitor.scount, visitor.fcount))
When we make and run an EditVisitor, a text editor is started with the os.system
command-line spawn call, which usually blocks its caller until the spawned program
finishes. As coded, when run on my machines, each time this script finds a matched
file during the traversal, it starts up the vi text editor within the console window where
the script was started; exiting the editor resumes the tree walk.
Let’s find and edit some files. When run as a script, we pass this program the search
string as a command argument (here, the string mimetypes is the search key). The root
directory passed to the run method is either the second argument or “.” (the current
run directory) by default. Traversal status messages show up in the console, but each
matched file now automatically pops up in a text editor along the way. In the following,
the editor is started eight times—try this with an editor and tree of your own to get a
better feel for how it works:
C:\...\PP4E\Tools> visitor_edit.py mimetypes C:\temp\PP3E\Examples
C:\temp\PP3E\Examples ...
1 => C:\temp\PP3E\Examples\README-root.txt
C:\temp\PP3E\Examples\PP3E ...
2 => C:\temp\PP3E\Examples\PP3E\echoEnvironment.pyw
3 => C:\temp\PP3E\Examples\PP3E\LaunchBrowser.pyw
4 => C:\temp\PP3E\Examples\PP3E\Launcher.py
5 => C:\temp\PP3E\Examples\PP3E\Launcher.pyc
Skipping C:\temp\PP3E\Examples\PP3E\Launcher.pyc
...more output omitted...
1427 => C:\temp\PP3E\Examples\PP3E\TempParts\lawnlake1-jan-03.jpg
Visitor: Walking Directories “++” | 335