"Locate" command in Python

Adonis adonisv at DELETETHISTEXTearthlink.net
Sun Apr 9 22:45:21 EDT 2006


mwt wrote:
> Is there a function in python that does what "locate" does in a bash
> shell?
> 
> I know I could do it by using os.popen('locate'), but I'm curious if
> there's a Python "native" way to go about it. Only needs to work in
> Unix, but would be interesting if it was cross-platform. 
> 
> Thanks.
> 

Here is a quick hack I just did, its very ugly, but does the job.

First do locate -u to create a cache then just locate [term], its not so 
fancy as to remind you when the cache is too old, but hey.

It requires Python 2.3+

Hope this helps.

Adonis


---

import os
import sys

rootPath = "/"

def search(term):
     if os.path.exists("files.cache"):
         cache = file("files.cache", 'r')
         for line in cache:
             if term in line:
                 print line.strip()
         cache.close()
     else:
         print "Please update the cache"

def cache():
     cache = file("files.cache", 'w')
     for root, dirs, files in os.walk(rootPath):
         for aDir in dirs:
             cache.write("%s\n" % aDir)
         for aFile in files:
             filePath = os.path.join(root, aFile)
             filePath = os.path.normpath(filePath)
             cache.write("%s\n" % filePath)
     cache.close()

if __name__ == "__main__":
     try:
         if sys.argv[1] == "-u":
             cache()
         else:
             search(sys.argv[1])
     except IndexError:
         print "Usage: locate [-u] [term]"



More information about the Python-list mailing list