3 useful Python scritps
I use Python more and more for simple scripting - it really excels at this! The scripts I create with Python are very simple and easy to understand (unlike many Perl or shell scripts).
Here are 3 useful Python scripts that I wrote for some time ago. Clean .pyc files
I use Subversion for version control and I don't version the .pyc (Python import os, sys
def pyc_clean(dir):
findcmd = 'find %s -name "*.pyc" -print' % dir
count = 0
for f in os.popen(findcmd).readlines():
count += 1
print str(f[:-1])
os.remove(str(f[:-1]))
print "Removed %d .pyc files" % count
if __name__ ==
"__main__":
pyc_clean(".")
Searching for something specific with PythonI wanted to find "cherrypy.request" in all the files, but not in the .svn directories (which are Subversion's directories). I tried to solve this with Unix tools, reading some manuals, Goggling after an answer, but at last I gave up and wrote a simple Python script in 2 minutes... import os, sys
findcmd = 'grep -R
"cherrpy.request" .'
print "Searching...:"
for f in os.popen(findcmd).readlines():
if str(f[:-1]).find(".svn") == -1:
print str(f[:-1])
Thanks to Kate for pointing out the grep equivalent. It is smarter and faster, but harder to find. Note to self: remember the -v option (invert match). grep -r "cherrpy.request" * | grep -v ".svn" Search and replace with PythonI had to replace every instance of "mosaicCMS" to "skeletonz" in .tmpl and .py files. I Goggled a bit, but didn't find anything that could solve my problem. I could have tried to find special search and replace application, but it's not my style. What did I do? I wrote my own little Python script to handle this little problem. Maybe an overkill, but it solved my problem :] import os, sys
count = 0
def rename(filetypes, oldname, newname):
global count
for filetype in filetypes:
findcmd = 'find . -name "*.%s" -print' % filetype
for f in os.popen(findcmd).readlines():
file = str(f[:-1])
count += 1
print str("Rename %s" % file)
os.popen('sed -e "s/%s/%s/g" %s > %s.tmp'
% (oldname, newname, file, file))
os.popen('cat %s.tmp > %s' % (file, file))
os.remove("%s.tmp" % file)
rename(["py", "tmpl"], "mosaicCMS", "skeletonz")
print "Changed %s files" % count
|
|