Locating commands with a simple Python script

This script is pretty simple. It lets you find commands by entering a string. Any commands which contain that string will be displayed. For example, running python cmdfind.py find returns:

./cmdfind.py
/sbin/findfs
/usr/X11R6/bin/find
/usr/X11R6/bin/find2perl
/usr/X11R6/bin/findsmb
/usr/X11R6/bin/gst-typefind-0.8
/usr/X11R6/bin/xfindproxy
/usr/bin/find
/usr/bin/find2perl
/usr/bin/findsmb
/usr/bin/gst-typefind-0.8
/usr/bin/xfindproxy
/usr/kde/3.3/bin/dcopfind
/usr/kde/3.3/bin/kappfinder
/usr/kde/3.3/bin/kfind
/usr/qt/3/bin/findtr

Here is the script itself:

#!/usr/bin/python2.3

“”"
This script does a partial search for a command name in your path.

Usage:
cmdfind
cmdfind –help
“”"

import sys
import glob
import os

def find(name):
“”"This scripts searches for the name in your path.”"”

search_pattern = “*” + name + “*”
initial_path = os.environ[’PATH’].split(’:')

# Strip duplicates
path = { }
for dir in initial_path:
path[dir] = dir
files = [ ]
for directory in path.keys():
glob_pattern = os.path.join(directory, search_pattern)
files.extend(glob.glob(glob_pattern))

# Sort and remove duplicates
final_files = { }
for file in files:
final_files[file] = file

commands = final_files.keys()
commands.sort()
if len(commands) > 0:
print “\n”.join(commands)
else:
print “No commands found.”

if __name__ == ‘__main__’:
if len(sys.argv) == 2 and sys.argv[1] != ‘–help’:
find(sys.argv[1])
else:
print __doc__

Note the use of dictionaries to create a list without duplicates. This is a trick I picked up from the Python Cookbook. The second instance of stripping duplicates probably isn’t needed–if the original path was stripped, then the final outputs should be stripped as well.

The other trick I like is using the __doc__ string as the usage message.

This script shows the power of the “batteris are included” philosophy in Python. The libraries provide enough power to make a script like this easy to write. The nice part about scripting languages is the easy integration with the shell and the operating system.

Book News:
Palm and Treo Hacks is now available for purchase at Amazon! It actually went live yesterday. The page has changed from “preorder” to “this title usually ships within 24 hours”. I’m going to start scouting book stores now to see when it shows up.

– Scott

Leave a Reply

You must be logged in to post a comment.