cpython/Tools/scripts/findlinksto.py

44 lines
1.0 KiB
Python
Raw Normal View History

#! /usr/bin/env python3
1991-06-04 17:36:54 -03:00
# findlinksto
#
# find symbolic links to a path matching a regular expression
1991-06-04 17:36:54 -03:00
import os
import sys
import re
import getopt
1991-06-04 17:36:54 -03:00
def main():
2001-01-17 04:48:39 -04:00
try:
opts, args = getopt.getopt(sys.argv[1:], '')
if len(args) < 2:
raise getopt.GetoptError('not enough arguments', None)
except getopt.GetoptError as msg:
2001-01-17 04:48:39 -04:00
sys.stdout = sys.stderr
print(msg)
print('usage: findlinksto pattern directory ...')
2001-01-17 04:48:39 -04:00
sys.exit(2)
pat, dirs = args[0], args[1:]
prog = re.compile(pat)
2001-01-17 04:48:39 -04:00
for dirname in dirs:
2008-05-09 17:00:17 -03:00
os.walk(dirname, visit, prog)
def visit(prog, dirname, names):
2001-01-17 04:48:39 -04:00
if os.path.islink(dirname):
names[:] = []
return
if os.path.ismount(dirname):
print('descend into', dirname)
2001-01-17 04:48:39 -04:00
for name in names:
name = os.path.join(dirname, name)
try:
linkto = os.readlink(name)
if prog.search(linkto) is not None:
print(name, '->', linkto)
except OSError:
2001-01-17 04:48:39 -04:00
pass
1991-06-04 17:36:54 -03:00
if __name__ == '__main__':
main()