Re: "Locate" command in Python
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: "Locate" command in Python

From: Adonis <adonisv@DELETETHISTEXTearthlink.net>
Date: Mon Apr 10 2006 - 04:45:21 CEST

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]"
Received on Sun Apr 30 22:39:54 2006