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

(yzsuai) #1

This script works, but it’s a bit more manual and code-y than it needs to be. In fact,
now that we also know about find operations, writing scripts based upon them is almost
trivial when we just need to match filenames. Example 6-15, for instance, falls back on
spawning shell find commands if you have them.


Example 6-15. PP4E\Tools\cleanpyc-find-shell.py


"""
find and delete all "*.pyc" bytecode files at and below the directory
named on the command-line; assumes a nonportable Unix-like find command
"""


import os, sys


rundir = sys.argv[1]
if sys.platform[:3] == 'win':
findcmd = r'c:\cygwin\bin\find %s -name ".pyc" -print' % rundir
else:
findcmd = 'find %s -name "
.pyc" -print' % rundir
print(findcmd)


count = 0
for fileline in os.popen(findcmd): # for all result lines
count += 1 # have \n at the end
print(fileline, end='')
os.remove(fileline.rstrip())


print('Removed %d .pyc files' % count)


When run, files returned by the shell command are removed:


C:\...\PP4E\Tools> cleanpyc-find-shell.py.
c:\cygwin\bin\find. -name "*.pyc" -print
./find.pyc
./visitor.pyc
./__init__.pyc
Removed 3 .pyc files

This script uses os.popen to collect the output of a Cygwin find program installed on
one of my Windows computers, or else the standard find tool on the Linux side. It’s
also completely nonportable to Windows machines that don’t have the Unix-like find
program installed, and that includes other computers of my own (not to mention those
throughout most of the world at large). As we’ve seen, spawning shell commands also
incurs performance penalties for starting a new program.


We can do much better on the portability and performance fronts and still retain code
simplicity, by applying the find tool we wrote in Python in the prior section. The new
script is shown in Example 6-16.


Example 6-16. PP4E\Tools\cleanpyc-find-py.py


"""
find and delete all "*.pyc" bytecode files at and below the directory
named on the command-line; this uses a Python-coded find utility, and


326 | Chapter 6: Complete System Programs

Free download pdf