/Tools/scripts/which.py

http://unladen-swallow.googlecode.com/ · Python · 60 lines · 46 code · 10 blank · 4 comment · 19 complexity · f68095554ac9d388273acb13e8e4554c MD5 · raw file

  1. #! /usr/bin/env python
  2. # Variant of "which".
  3. # On stderr, near and total misses are reported.
  4. # '-l<flags>' argument adds ls -l<flags> of each file found.
  5. import sys
  6. if sys.path[0] in (".", ""): del sys.path[0]
  7. import sys, os
  8. from stat import *
  9. def msg(str):
  10. sys.stderr.write(str + '\n')
  11. def main():
  12. pathlist = os.environ['PATH'].split(os.pathsep)
  13. sts = 0
  14. longlist = ''
  15. if sys.argv[1:] and sys.argv[1][:2] == '-l':
  16. longlist = sys.argv[1]
  17. del sys.argv[1]
  18. for prog in sys.argv[1:]:
  19. ident = ()
  20. for dir in pathlist:
  21. filename = os.path.join(dir, prog)
  22. try:
  23. st = os.stat(filename)
  24. except os.error:
  25. continue
  26. if not S_ISREG(st[ST_MODE]):
  27. msg(filename + ': not a disk file')
  28. else:
  29. mode = S_IMODE(st[ST_MODE])
  30. if mode & 0111:
  31. if not ident:
  32. print filename
  33. ident = st[:3]
  34. else:
  35. if st[:3] == ident:
  36. s = 'same as: '
  37. else:
  38. s = 'also: '
  39. msg(s + filename)
  40. else:
  41. msg(filename + ': not executable')
  42. if longlist:
  43. sts = os.system('ls ' + longlist + ' ' + filename)
  44. if sts: msg('"ls -l" exit status: ' + repr(sts))
  45. if not ident:
  46. msg(prog + ': not found')
  47. sts = 1
  48. sys.exit(sts)
  49. if __name__ == '__main__':
  50. main()