findlinksto.py 1.05 KB
Newer Older
1
#! /usr/bin/env python3
Guido van Rossum's avatar
Guido van Rossum committed
2 3 4

# findlinksto
#
5
# find symbolic links to a path matching a regular expression
Guido van Rossum's avatar
Guido van Rossum committed
6

7 8
import os
import sys
9
import re
10
import getopt
Guido van Rossum's avatar
Guido van Rossum committed
11

12
def main():
Tim Peters's avatar
Tim Peters committed
13 14 15
    try:
        opts, args = getopt.getopt(sys.argv[1:], '')
        if len(args) < 2:
16
            raise getopt.GetoptError('not enough arguments', None)
17
    except getopt.GetoptError as msg:
Tim Peters's avatar
Tim Peters committed
18
        sys.stdout = sys.stderr
19 20
        print(msg)
        print('usage: findlinksto pattern directory ...')
Tim Peters's avatar
Tim Peters committed
21 22
        sys.exit(2)
    pat, dirs = args[0], args[1:]
23
    prog = re.compile(pat)
Tim Peters's avatar
Tim Peters committed
24
    for dirname in dirs:
25
        os.walk(dirname, visit, prog)
26 27

def visit(prog, dirname, names):
Tim Peters's avatar
Tim Peters committed
28 29 30 31
    if os.path.islink(dirname):
        names[:] = []
        return
    if os.path.ismount(dirname):
32
        print('descend into', dirname)
Tim Peters's avatar
Tim Peters committed
33 34 35 36
    for name in names:
        name = os.path.join(dirname, name)
        try:
            linkto = os.readlink(name)
37
            if prog.search(linkto) is not None:
38
                print(name, '->', linkto)
39
        except OSError:
Tim Peters's avatar
Tim Peters committed
40
            pass
Guido van Rossum's avatar
Guido van Rossum committed
41

42 43
if __name__ == '__main__':
    main()