1#! /usr/bin/env python3
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
8if sys.path[0] in (".", ""): del sys.path[0]
9
10import sys, os
11from stat import *
12
13def msg(str):
14    sys.stderr.write(str + '\n')
15
16def main():
17    pathlist = os.environ['PATH'].split(os.pathsep)
18
19    sts = 0
20    longlist = ''
21
22    if sys.argv[1:] and sys.argv[1][:2] == '-l':
23        longlist = sys.argv[1]
24        del sys.argv[1]
25
26    for prog in sys.argv[1:]:
27        ident = ()
28        for dir in pathlist:
29            filename = os.path.join(dir, prog)
30            try:
31                st = os.stat(filename)
32            except OSError:
33                continue
34            if not S_ISREG(st[ST_MODE]):
35                msg(filename + ': not a disk file')
36            else:
37                mode = S_IMODE(st[ST_MODE])
38                if mode & 0o111:
39                    if not ident:
40                        print(filename)
41                        ident = st[:3]
42                    else:
43                        if st[:3] == ident:
44                            s = 'same as: '
45                        else:
46                            s = 'also: '
47                        msg(s + filename)
48                else:
49                    msg(filename + ': not executable')
50            if longlist:
51                sts = os.system('ls ' + longlist + ' ' + filename)
52                if sts: msg('"ls -l" exit status: ' + repr(sts))
53        if not ident:
54            msg(prog + ': not found')
55            sts = 1
56
57    sys.exit(sts)
58
59if __name__ == '__main__':
60    main()
61