473,657 Members | 2,270 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

"Locate" command in Python

mwt
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('locat e'), 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.

Apr 10 '06 #1
7 10923
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('locat e'), 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.cach e"):
cache = file("files.cac he", '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.cac he", 'w')
for root, dirs, files in os.walk(rootPat h):
for aDir in dirs:
cache.write("%s \n" % aDir)
for aFile in files:
filePath = os.path.join(ro ot, aFile)
filePath = os.path.normpat h(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]"
Apr 10 '06 #2
How about one of these that works on Windows XP? I know there's no
files.cache, but I wonder if your script could be combined with another
function that would generate a list of paths on a Windows XP machine.

Anyway, thanks for the script.

Apr 10 '06 #3
BartlebyScriven er wrote:
How about one of these that works on Windows XP? I know there's no
files.cache, but I wonder if your script could be combined with another
function that would generate a list of paths on a Windows XP machine.

Anyway, thanks for the script.


I wrote it on a Windows XP machine. The files.cache is generated when
you use the -u option. For example if you saved the script as locate.py
first at a command prompt: python locate.py -u this will create the
files.cache, it simply walks through your entire hard drive writing all
the directories and files it finds along the way. Then doing: python
locate.py SomeFileOrDirNa me will go through the files.cache matching
whatever term your looking for if present. Although the rootPath
variable is set to the POSIX style path of "/" Python converts it to a
proper path. At least thats my assumption as it works fine on my system.

Adonis
Apr 10 '06 #4
Adonis,

Cool! I'm on it.

Thanks again.

rpd

Apr 10 '06 #5
This script is COOL. It should be in the next cookbook. Maybe with some
tweaks and switches.

Thanks again.

Rick

Apr 10 '06 #6
mwt
On my system, files.cache ended up being 45.9 Mb (800,000+ lines)!
Pretty fun script. I can imagine some interesting variations.
Thanks!

Apr 10 '06 #7
>>45.9 mb

Yikes.

I keep all of my data files on a separate logical drive. I indexed only
that one. I'm going to try and figure a way to store the results of
os.walk(root) as a shelve, and then search it that way.

In the meantime, you might try the script we were playing with in the
previous thread.
It's from the Python Cookbook. It doesn't create a file for searching,
but gets the job done.

http://groups.google.com/group/comp....e36791afbb90b8

I'm thinking there is a way to crossbreed this script with Adonis's for
something lightning fast.

I'll post it if I get free time to make it.

rpd

Apr 10 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
10272
by: francescomoi | last post by:
Hi. I'm trying to build 'MySQL-python-1.2.0' on my Linux FC2: ---------------------------------- # export PATH=$PATH:/usr/local/mysql/bin/ # export mysqlclient=mysqlclient_r # python setup.py clean # python setup.py build running build running build_py
1
15873
by: francescomoi | last post by:
Hi. I'm trying to build MySQL-python-1.2.0 on my Linux FC2 (with MySQL 3.23.58). But when building, I get this error message: ------------------------------------------------------- # python setup.py build running build running build_py running build_ext building '_mysql' extension
33
2310
by: Frederick Gotham | last post by:
(My dialect of English seems to puzzle people at times, so I'll first clarify a few terms which I use in the following post:) (1) By "domestic", I mean "ordinary, run-of-the-mill, not extraordinary or strange". (2) By "willy-nilly", I mean something along the lines of "haphazardly", but without any sense of recklessness (i.e. gleefully doing something without expecting any sort of negative effect, even though there may in fact be a...
0
1241
by: skip | last post by:
After much wailing and gnashing of teeth the past couple of days, I managed to move (most of?) the content from the MacPython wiki to the main Python wiki (*). All pages were created as subpages of http://wiki.python.or/moin/MacPython The motivation for this rather hasty move was that the MacPython wiki was running an ancient version of MoinMoin and got spammed heavily. Because of its age and vulnerability it was simply too hard to...
14
7146
by: Nader Emami | last post by:
I have installed "TurboGears" and I would install 'pysqlite' also. I am a user on a Linux machine. If I try to install the 'pysqlite' with 'easy_install' tool I get the next error message. The error message is longer than what I send here. % easy_install pysqlite Searching for pysqlite Reading http://cheeseshop.python.org/pypi/pysqlite/ Reading http://pysqlite.org/
0
1260
by: CtrlAltDel2008 | last post by:
Hello everyone, i hope you can help me with this query. The code below all works fine, referring to the SUBSTRING part, at the moment it just displays all the text from the "http" part until the end of the thread. I am trying to get it to just grab the URL and display that only. $sql= <<< END SELECT post_date , DATE_FORMAT(FROM_UNIXTIME( post_date ) , '%d-%m-%Y') AS formatted_date , LEFT(title, 30) AS title , post
3
1176
by: dwblas | last post by:
The annual Linux Journal survey is online now for any Linux users who want to vote for Python. http://www.linuxjournal.com/node/1006101
1
2020
by: perlvasu | last post by:
6 jobs are running at the same time and accessing same dbm file for writing and reading. These are daily jobs and failing only some times not regularly. So i thought of this is just because of dead lock situation. So i tried to put flock here in the following code. But i got the following error. Can't locate object method "fd" via package "SDBM_File" Can any body help me in this case. use strict ; use warnings ; use SDBM_File ;
12
18261
by: Jordi | last post by:
I'm getting the following error: Software error: Can't locate object method "new" via package "A::B" at /path/file.cgi line 5. My code is basically this: #!/usr/bin/perl -w use strict; use warnings; use A::B; my $test = new A::B;
0
8323
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8838
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8739
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8513
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7351
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6176
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5638
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4329
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1732
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.