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