Skip to content

Instantly share code, notes, and snippets.

@enlavin
Created November 8, 2010 16:31
Show Gist options
  • Save enlavin/667891 to your computer and use it in GitHub Desktop.
Save enlavin/667891 to your computer and use it in GitHub Desktop.
Simple "which" implementation in python featuring partial matching
#!python.exe
"""which command substitute with partial matching search"""
import glob
import os
import sys
try:
partial_fname = sys.argv[1]
except IndexError:
print "which.py <filename>"
sys.exit(1)
results = {'partial': [], 'exact': []}
path_list = ["."] + [path.rstrip().lstrip() for path in os.environ["PATH"].split(";")]
for d in path_list:
try:
full_name = os.path.join(d,partial_fname)
os.stat(full_name)
results['exact'].append(full_name)
except:
# partial matching
all_files = glob.glob(os.path.join(d, "*%s*" % partial_fname))
for f in all_files:
results['partial'].append(f)
for f in results['exact']:
print " %s" % f
for f in results['partial']:
print "P %s" % f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment