if name == 'main':
import sys
namepattern, startdir = sys.argv[1], sys.argv[2]
for name in find(namepattern, startdir): print(name)
There’s not much to this file—it’s largely just a minor extension to os.walk—but calling
its find function provides the same utility as both the deprecated find standard library
module and the Unix utility of the same name. It’s also much more portable, and no-
ticeably easier than repeating all of this file’s code every time you need to perform a
find-type search. Because this file is instrumented to be both a script and a library, it
can also be both run as a command-line tool or called from other programs.
For instance, to process every Python file in the directory tree rooted one level up from
the current working directory, I simply run the following command line from a system
console window. Run this yourself to watch its progress; the script’s standard output
is piped into the more command to page it here, but it can be piped into any processing
program that reads its input from the standard input stream:
C:\...\PP4E\Tools> python find.py *.py .. | more
..\LaunchBrowser.py
..\Launcher.py
..\__init__.py
..\Preview\attachgui.py
..\Preview\customizegui.py
...more lines omitted...
For more control, run the following sort of Python code from a script or interactive
prompt. In this mode, you can apply any operation to the found files that the Python
language provides:
C:\...\PP4E\System\Filetools> python
>>> from PP4E.Tools import find # or just import find if in cwd
>>> for filename in find.find('*.py', '..'):
... if 'walk' in open(filename).read():
... print(filename)
...
..\Launcher.py
..\System\Filetools\bigext-tree.py
..\System\Filetools\bigpy-path.py
..\System\Filetools\bigpy-tree.py
..\Tools\cleanpyc.py
..\Tools\find.py
..\Tools\visitor.py
Notice how this avoids having to recode the nested loop structure required for
os.walk every time you want a list of matching file names; for many use cases, this seems
conceptually simpler. Also note that because this finder is a generator function, your
script doesn’t have to wait until all matching files have been found and collected;
os.walk yields results as it goes, and find.find yields matching files among that set.
Here’s a more complex example of our find module at work: the following system
command line lists all Python files in directory C:\temp\PP3E whose names begin with
322 | Chapter 6: Complete System Programs